问题:
# 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
#
# 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
#
# 此外,你可以假设该网格的四条边均被水包围。
#
#
#
# 示例 1:
#
#
# 输入:grid = [
# ["1","1","1","1","0"],
# ["1","1","0","1","0"],
# ["1","1","0","0","0"],
# ["0","0","0","0","0"]
# ]
# 输出:1
方法:dfs,bfs,并查集
# leetcode submit region begin(Prohibit modification and deletion) class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 m, n = len(grid), len(grid[0]) count = 0 def dfs(i, j): # 数据抹零 grid[i][j] = '0' # 查找上下左右 for dx, dy in [[1, 0], [-1, 0], [0, 1], [0, -1]]: x, y = i + dx, j + dy if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': dfs(x, y) for i in range(m): for j in range(n): if grid[i][j] == '1': count += 1 dfs(i, j) return count # leetcode submit region end(Prohibit modification and deletion)