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