订正文件0099.岛屿的数量广搜.md文件,python部分用的是深搜算法

This commit is contained in:
liujiahang
2024-08-12 00:57:42 +08:00
parent 37af407632
commit 49aa077428

View File

@ -246,29 +246,36 @@ public class Main {
```python ```python
def dfs(grid, visited, x, y): from collections import deque
dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 四个方向 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
for d in dir: def bfs(grid, visited, x, y):
nextx, nexty = x + d[0], y + d[1] que = deque([])
if 0 <= nextx < len(grid) and 0 <= nexty < len(grid[0]): que.append([x,y])
if not visited[nextx][nexty] and grid[nextx][nexty] == 1: # 没有访问过的 同时 是陆地的 while que:
visited[nextx][nexty] = True cur_x, cur_y = que.popleft()
dfs(grid, visited, nextx, nexty) 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(): def main():
n, m = map(int, input().split()) 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)] visited = [[False] * m for _ in range(n)]
res = 0
result = 0
for i in range(n): for i in range(n):
for j in range(m): for j in range(m):
if not visited[i][j] and grid[i][j] == 1: if grid[i][j] == 1 and not visited[i][j]:
visited[i][j] = True res += 1
result += 1 # 遇到没访问过的陆地,+1 bfs(grid, visited, i, j)
dfs(grid, visited, i, j) # 将与其链接的陆地都标记上 True print(res)
print(result)
if __name__ == "__main__": if __name__ == "__main__":
main() main()