讨论/《广度优先搜索》 - 练习:岛屿数量/
《广度优先搜索》 - 练习:岛屿数量
共 1 个回复
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]: return 0
        res = 0
        n, m = len(grid), len(grid[0])
        directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
        for i in range(n):
            for j in range(m):
                if grid[i][j] == "0":
                    continue
                res += 1
                grid[i][j] = "0"
                print(i, j)
                q = collections.deque([(i, j)])
                while q:
                    x, y = q.popleft()
                    for _x, _y in directions:
                        next_x, next_y = x + _x, y + _y
                        if 0 <= next_x < n and 0 <= next_y < m and grid[next_x][next_y] == "1":
                            grid[next_x][next_y] = "0"
                            q.append((next_x, next_y))
        return res