AcWing 844. 走迷宫 -python3
原题链接
简单
作者:
机械佬也想学编程
,
2020-07-06 21:14:17
,
所有人可见
,
阅读 457
n, m = map(int, input().split())
s = [] # 存放迷宫数组
for i in range(n):
s.append(list(map(int, input().split())))
queue = [(0,0)] * (n * m) # 该队列存放路径上每个点的坐标
d = [[-1] * m for i in range(n)] # 索引代表坐标,存的值代表与起点的距离
d[0][0] = 0
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
def bfs():
hh, tt = 0, 0
while hh <= tt:
x, y = queue[hh]
hh += 1
for i in range(4): # 探索(x,y)上下左右四个点
nx = x + dx[i]
ny = y + dy[i]
if nx >= 0 and nx < n and ny >= 0 and ny < m and s[nx][ny] == 0 and d[nx][ny] == -1:
d[nx][ny] = d[x][y] + 1
tt += 1
queue[tt] = (nx, ny)
return d[n-1][m-1]
print(bfs())