leetcode200. 岛屿的个数

给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3

对每一个为1的位置四个方向搜索,注意将搜过的地方置为0:

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        res, self.x, self.y = 0, len(grid), len(grid[0])
        for i in range(self.x):
            for j in range(self.y):
                if grid[i][j] == '1':  # 置为0
                    res += 1
                    grid[i][j] = '0'
                    self.helper(grid, i, j)
        return res

    def helper(self, grid, a, b):  # 上下左右
        for x,y in [(a-1, b), (a+1, b), (a, b-1), (a, b+1)]:
            if 0<=x<self.x and 0<=y<self.y and grid[x][y]=='1':
                grid[x][y] = '0'
                self.helper(grid, x, y)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章