@@ -246,29 +246,36 @@ public class Main {
246246
247247``` python
248248
249- def dfs (grid , visited , x , y ):
250- dir = [(0 , 1 ), (1 , 0 ), (- 1 , 0 ), (0 , - 1 )] # 四个方向
251- for d in dir :
252- nextx, nexty = x + d[0 ], y + d[1 ]
253- if 0 <= nextx < len (grid) and 0 <= nexty < len (grid[0 ]):
254- if not visited[nextx][nexty] and grid[nextx][nexty] == 1 : # 没有访问过的 同时 是陆地的
255- visited[nextx][nexty] = True
256- dfs(grid, visited, nextx, nexty)
249+ from collections import deque
250+ directions = [[0 , 1 ], [1 , 0 ], [0 , - 1 ], [- 1 , 0 ]]
251+ def bfs (grid , visited , x , y ):
252+ que = deque([])
253+ que.append([x,y])
254+ while que:
255+ cur_x, cur_y = que.popleft()
256+ for i, j in directions:
257+ next_x = cur_x + i
258+ next_y = cur_y + j
259+ if next_y < 0 or next_x < 0 or next_x >= len (grid) or next_y >= len (grid[0 ]):
260+ continue
261+ if not visited[next_x][next_y] and grid[next_x][next_y] == 1 :
262+ visited[next_x][next_y] = True
263+ que.append([next_x, next_y])
264+
257265
258266def main ():
259267 n, m = map (int , input ().split())
260- grid = [list (map (int , input ().split())) for _ in range (n)]
268+ grid = []
269+ for i in range (n):
270+ grid.append(list (map (int , input ().split())))
261271 visited = [[False ] * m for _ in range (n)]
262-
263- result = 0
272+ res = 0
264273 for i in range (n):
265274 for j in range (m):
266- if not visited[i][j] and grid[i][j] == 1 :
267- visited[i][j] = True
268- result += 1 # 遇到没访问过的陆地,+1
269- dfs(grid, visited, i, j) # 将与其链接的陆地都标记上 True
270-
271- print (result)
275+ if grid[i][j] == 1 and not visited[i][j]:
276+ res += 1
277+ bfs(grid, visited, i, j)
278+ print (res)
272279
273280if __name__ == " __main__" :
274281 main()
0 commit comments