Skip to content

Commit 612ff79

Browse files
committed
更新卡码99_增加Python3版本
1 parent c6635bb commit 612ff79

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

problems/kamacoder/0099.岛屿的数量广搜.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,56 @@ int main() {
192192

193193
### Python
194194

195+
```python
196+
from collections import deque
197+
198+
# 四个方向
199+
position = [[0, 1], [1, 0], [0, -1], [-1, 0]]
200+
201+
202+
def bfs(grid, visited, x, y):
203+
"""
204+
广度优先搜索对陆地进行标记
205+
"""
206+
207+
que = deque() # 创建队列
208+
209+
# 标记当前节点并加入队列
210+
visited[x][y] = True
211+
que.append([x, y])
212+
213+
while que:
214+
cur_x, cur_y = que.popleft() # 取出队首节点
215+
for i, j in position:
216+
next_x = cur_x + i
217+
next_y = cur_y + j
218+
# 下一节点下标越界,跳过
219+
if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
220+
continue
221+
# 下一节点是陆地且未被访问,标记节点并加入队列
222+
if grid[next_x][next_y] == 1 and not visited[next_x][next_y]:
223+
visited[next_x][next_y] = True
224+
que.append([next_x, next_y])
225+
226+
227+
n, m = map(int, input().split())
228+
# 邻接矩阵
229+
grid = []
230+
for i in range(n):
231+
grid.append(list(map(int, input().split())))
232+
233+
visited = [[False] * m for _ in range(n)] # 访问表
234+
235+
res = 0
236+
for i in range(n):
237+
for j in range(m):
238+
if grid[i][j] == 1 and not visited[i][j]:
239+
res += 1
240+
bfs(grid, visited, i, j)
241+
242+
print(res)
243+
```
244+
195245
### Go
196246

197247
### Rust

0 commit comments

Comments
 (0)