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