题解 | 走迷宫

走迷宫

https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64

import sys
from collections import deque

n,m = map(int,input().split())
xs,ys,xt,yt = map(int,input().strip().split())
xs-=1; ys-=1; xt-=1; yt-=1
# print(xs,ys,xt,yt)

grid = []
for _ in range(n):
    grid.append(input().strip())

steps = 0
dirs = [(-1,0),(1,0),(0,-1),(0,1)]
# bfs 初始化
queue = deque()
visted = [[False]*m for _ in range(n)]
queue.append((xs,ys,steps))
visted[xs][ys] = True

found = False
result = -1

while queue:
    x,y,steps = queue.popleft()

    if x==xt and y==yt: # 出口
        found = True
        result = steps
    
    for dx,dy in dirs:
        nx,ny = x+dx,y+dy
        if 0<=nx<n and 0<=ny<m:
            if not visted[nx][ny] and grid[nx][ny] == '.':
                queue.append((nx,ny,steps+1))
                visted[nx][ny] = True

if not found:
    print(-1)
else:
    print(result)


全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务