diff --git a/problems/kamacoder/0099.岛屿的数量广搜.md b/problems/kamacoder/0099.岛屿的数量广搜.md index 3c069b44..9771877b 100644 --- a/problems/kamacoder/0099.岛屿的数量广搜.md +++ b/problems/kamacoder/0099.岛屿的数量广搜.md @@ -246,29 +246,36 @@ public class Main { ```python -def dfs(grid, visited, x, y): - dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 四个方向 - for d in dir: - nextx, nexty = x + d[0], y + d[1] - if 0 <= nextx < len(grid) and 0 <= nexty < len(grid[0]): - if not visited[nextx][nexty] and grid[nextx][nexty] == 1: # 没有访问过的 同时 是陆地的 - visited[nextx][nexty] = True - dfs(grid, visited, nextx, nexty) +from collections import deque +directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] +def bfs(grid, visited, x, y): + que = deque([]) + que.append([x,y]) + while que: + cur_x, cur_y = que.popleft() + for i, j in directions: + next_x = cur_x + i + next_y = cur_y + j + if next_y < 0 or next_x < 0 or next_x >= len(grid) or next_y >= len(grid[0]): + continue + if not visited[next_x][next_y] and grid[next_x][next_y] == 1: + visited[next_x][next_y] = True + que.append([next_x, next_y]) + def main(): n, m = map(int, input().split()) - grid = [list(map(int, input().split())) for _ in range(n)] + grid = [] + for i in range(n): + grid.append(list(map(int, input().split()))) visited = [[False] * m for _ in range(n)] - - result = 0 + res = 0 for i in range(n): for j in range(m): - if not visited[i][j] and grid[i][j] == 1: - visited[i][j] = True - result += 1 # 遇到没访问过的陆地,+1 - dfs(grid, visited, i, j) # 将与其链接的陆地都标记上 True - - print(result) + if grid[i][j] == 1 and not visited[i][j]: + res += 1 + bfs(grid, visited, i, j) + print(res) if __name__ == "__main__": main()