AcWing 1076. 迷宫问题 简单BFS
原题链接
简单
作者:
皓首不倦
,
2020-08-01 15:19:11
,
所有人可见
,
阅读 441
from collections import deque
grid = []
n = int(input())
for i in range(n):
grid.append( list(map(int, input().split())) )
prev = {(0, 0): None}
que = deque()
que.append((0, 0))
visited = [[0] * n for _ in range(n)]
visited[0][0] = 1
while len(que) > 0:
i, j = que.popleft()
if i == n-1 and j == n-1:
break
for ii, jj in [[i-1, j], [i+1, j], [i, j-1], [i, j+1]]:
if ii >= 0 and ii < n and jj >= 0 and jj < n and visited[ii][jj] == 0 and grid[ii][jj] == 0:
visited[ii][jj] = 1
que.append((ii, jj))
prev[(ii, jj)] = (i, j)
cur = (n-1, n-1)
que = deque()
while cur != None:
que.appendleft((cur))
cur = prev[cur]
for i, j in que:
print(i, j)