Lintcode 433. Number of Islands

433. Number of Islands

Description:

Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Find the number of islands.

Example
Given graph:

[
[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]
]
return 3.

Code:

class Solution:
    """
    @param grid: a boolean 2D matrix
    @return: an integer
    """
    def numIslands(self, grid):
        # Write your code here
        m = len(grid)
        if m==0:
            return 0
        n = len(grid[0])
        if  n==0:
            return 0
        count = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j]==True:
                    self.islandErase(grid,i,j)
                    count +=1
        return count

    def islandErase(self,grid,i,j):
        if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]):
            return
        if grid[i][j]==True:
            grid[i][j]=False
            self.islandErase(grid,i-1,j)
            self.islandErase(grid,i+1,j)
            self.islandErase(grid,i,j-1)
            self.islandErase(grid,i,j+1)

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/80939971