From 612ff79f4f2e1efe60511f52d27d510e9eb417fe Mon Sep 17 00:00:00 2001 From: kimoge <1579457263@qq.com> Date: Fri, 19 Jul 2024 10:41:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=8D=A1=E7=A0=8199=5F?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kamacoder/0099.岛屿的数量广搜.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/kamacoder/0099.岛屿的数量广搜.md b/problems/kamacoder/0099.岛屿的数量广搜.md index b9bdb796..def79bf7 100644 --- a/problems/kamacoder/0099.岛屿的数量广搜.md +++ b/problems/kamacoder/0099.岛屿的数量广搜.md @@ -192,6 +192,56 @@ int main() { ### Python +```python +from collections import deque + +# 四个方向 +position = [[0, 1], [1, 0], [0, -1], [-1, 0]] + + +def bfs(grid, visited, x, y): + """ + 广度优先搜索对陆地进行标记 + """ + + que = deque() # 创建队列 + + # 标记当前节点并加入队列 + visited[x][y] = True + que.append([x, y]) + + while que: + cur_x, cur_y = que.popleft() # 取出队首节点 + for i, j in position: + next_x = cur_x + i + next_y = cur_y + j + # 下一节点下标越界,跳过 + if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]): + continue + # 下一节点是陆地且未被访问,标记节点并加入队列 + if grid[next_x][next_y] == 1 and not visited[next_x][next_y]: + visited[next_x][next_y] = True + que.append([next_x, next_y]) + + +n, m = map(int, input().split()) +# 邻接矩阵 +grid = [] +for i in range(n): + grid.append(list(map(int, input().split()))) + +visited = [[False] * m for _ in range(n)] # 访问表 + +res = 0 +for i in range(n): + for j in range(m): + if grid[i][j] == 1 and not visited[i][j]: + res += 1 + bfs(grid, visited, i, j) + +print(res) +``` + ### Go ### Rust