在写 “广度优先遍历” 的时候,要注意一点:所有加入队列的结点,都应该马上被标记为 “已经访问”,否则有可能会被重复加入队列。
如果等到队列出队的时候才标记 “已经访问”,事实上,这种做法是错误的。因为如果不在刚刚入队列的时候标记 “已经访问”,相同的结点很可能会重复入队
from queue import Queue class Solution: def numIslands(self, grid: List[List[str]]) -> int: if len(grid) == 0 or len(grid[0]) == 0: return 0 m, n = len(grid), len(grid[0]) islandCount = 0 visited = [[False] * n for i in range(m)] for i in range(m): for j in range(n): if not visited[i][j] and grid[i][j] == '1': islandCount += 1 # use bfs to flood que = Queue() que.put((i, j)) visited[i][j] = True while not que.empty(): x, y = que.get() for dx , dy in [(-1, 0), (0, -1), (0, 1), (1, 0)]: if x + dx >= 0 and x + dx < m and y + dy >= 0 and y + dy < n: if not visited[x + dx][y + dy] and grid[x + dx][y + dy] == '1': que.put((x + dx, y + dy)) visited[x + dx][y + dy] = True return islandCount