在写 “广度优先遍历” 的时候,要注意一点:所有加入队列的结点,都应该马上被标记为 “已经访问”,否则有可能会被重复加入队列。

如果等到队列出队的时候才标记 “已经访问”,事实上,这种做法是错误的。因为如果不在刚刚入队列的时候标记 “已经访问”,相同的结点很可能会重复入队

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

  

相关文章:

  • 2022-03-10
  • 2021-07-31
  • 2021-08-23
  • 2021-09-02
  • 2021-07-27
  • 2021-05-20
猜你喜欢
  • 2021-09-14
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
  • 2022-03-03
  • 2021-08-14
  • 2022-01-08
相关资源
相似解决方案