题解 | 走迷宫
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
from collections import deque
n,m = list(map(int,input().split()))
xs,ys,xt,yt = map(int,input().split())
xs -= 1
ys -= 1
xt -= 1
yt -= 1
grid = [input() for _ in range(n)]
visit = [[False]*m for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
q = deque()
q.append((xs,ys))
visit[xs][ys]=True
step = 0
while q:
size = len(q)
for _ in range(size):
x,y = q.popleft()
if x==xt and y==yt:
print(step)
exit()
for i in range(4):
nx = x+dx[i]
ny = y+dy[i]
if nx>=0 and nx<n and ny>=0 and ny<m:
if not visit[nx][ny] and grid[nx][ny]=='.':
visit[nx][ny]=True
q.append((nx,ny))
step += 1
print(-1)
查看25道真题和解析