From 49aa077428baef0079a7ef22e82b8a113eca4f40 Mon Sep 17 00:00:00 2001 From: liujiahang Date: Mon, 12 Aug 2024 00:57:42 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=A2=E6=AD=A3=E6=96=87=E4=BB=B60099.?= =?UTF-8?q?=E5=B2=9B=E5=B1=BF=E7=9A=84=E6=95=B0=E9=87=8F=E5=B9=BF=E6=90=9C?= =?UTF-8?q?.md=E6=96=87=E4=BB=B6=EF=BC=8Cpython=E9=83=A8=E5=88=86=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E6=98=AF=E6=B7=B1=E6=90=9C=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kamacoder/0099.岛屿的数量广搜.md | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) 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()