leetcode(58)-岛屿数量

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        height = len(grid)
        width = len(grid[0])
        num_of_island = 1
        def infect(i,j):
            four_directions  = [(0,-1),(1,0),(-1,0),(0,1)]
            for (x,y) in four_directions:
                new_i, new_j = i+x, j+y
                if 0<=new_i<height and 0<=new_j<width:
                    if grid[new_i][new_j] == "1":
                        grid[new_i][new_j] = num_of_island
                        infect(new_i,new_j)
        

        for i in range(height):
            for j in range(width):
                if grid[i][j] == "1":

                    num_of_island+=1
                    grid[i][j] = num_of_island
                    infect(i,j)
        return num_of_island-1
posted @ 2020-10-16 20:15  木子士心王大可  阅读(107)  评论(0)    收藏  举报