题目标题

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

参考解析
  1. class Solution:
  2. def numIslands(self, grid: List[List[str]]) -> int:
  3. nr = len(grid)
  4. if nr == 0:
  5. return 0
  6. nc = len(grid[0])
  7. num_islands = 0
  8. for r in range(nr):
  9. for c in range(nc):
  10. if grid[r][c] == "1":
  11. num_islands += 1
  12. grid[r][c] = "0"
  13. neighbors = collections.deque([(r, c)])
  14. while neighbors:
  15. row, col = neighbors.popleft()
  16. for x, y in [(row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)]:
  17. if 0 <= x < nr and 0 <= y < nc and grid[x][y] == "1":
  18. neighbors.append((x, y))
  19. grid[x][y] = "0"
  20. return num_islands