Lintcode Python Simple Level topic 433. Number of islands

Source: Internet
Author: User

Title Description:

Give a 01 matrix to find the number of different islands.

0 represents the sea, 1 represents the island, if two 1 are adjacent, then the two 1 belong to the same island. We only consider the next and next left and right adjacent.

Have you ever encountered this problem in a real interview? Yes Sample Example

In The matrix:

[  [1, 1, 0, 0, 0],  [0, 1, 0, 0, 1],  [0, 0, 0, 1, 1],  [0, 0, 0, 0, 0],  [0, 0, 0, 0, 1]]

There is 3 an island in the middle.

labelFace book Google Zenefits

Topic Analysis:

Loop a 2-dimensional array, find the element whose value is 1, count++,

And then recursively change the value of the element to 1 for the upper and lower left to 0,

The loop continues.

Source:

Class Solution: # @param {boolean[][]} grid a Boolean 2D matrix # @return {int} an integer def numislands (self, g RID): # Write Your code here if the grid is None:return None if Grid = = []: return 0 # When the array is not empty, the calculation Number of rows and columns SELF.N = Len (grid) self.m = Len (grid[0]) x = 0 for I in range (SELF.N): for J In range (SELF.M): if grid[i][j] = = 1:x + 1 Grid = Self.change (grid,            I,J) return x def change (self,grid,i,j): grid[i][j] = 0 if i > 0 and grid[i-1][j] = = 1:            # The point at the top of the current point is 0 Grid = Self.change (grid,i-1,j) If I < self.n-1 and grid[i+1][j] = = 1:            # Place the point below the current point at 0 Grid = Self.change (grid,i+1,j) if J < self.m-1 and grid[i][j+1] = = 1: # The point to the right of the current point is 0 Grid = Self.change (grid,i,j+1) if J > 0 and grid[i][j-1] = = 1: # Place the current point to the left The point is 0 Grid = sElf.change (grid,i,j-1) return grid 

Lintcode Python Simple level topic 433. Number of islands

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.