-
[题目链接](200. 岛屿数量 - 力扣(LeetCode))
-
解题思路:用感染函数,遇到1,岛屿数目就加1,然后递归把上下左右变成2(以免下次遇到相同的岛屿)
-
代码
class Solution: # 感染函数,将[i, j]感染 def process(self, grid, i, j): if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != '1': return grid[i][j] = '2' self.process(grid, i - 1, j) self.process(grid, i + 1, j) self.process(grid, i, j - 1) self.process(grid, i, j + 1) def numIslands(self, grid: List[List[str]]) -> int: ans = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': ans += 1 self.process(grid, i, j) return ans