给定一个大小为NXM的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。给出起点和终点坐标,请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。
10 10
0 1
9 8
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
from collections import deque
n,m=map(int,input().split())
sx,sy=map(int,input().split())
gx,gy=map(int,input().split())
maze=[]
for i in range(n):
list1=list(input())
maze.append(list1)
#print(maze)
d=[[float('inf')]*m for i in range(n)]
dx=[1,0,-1,0]
dy=[0,1,0,-1]
def bfs():
queue=deque()
#将起点加入队列,并把这一地点的距离设置为0
queue.append([sx,sy])
d[sx][sy]=0
while queue:
#从队列的最前端取出元素
p=queue.pop()
#如果取出的状态已经是终点,则结束搜索
if p[0]==gx and p[1]==gy:
break
#四个方向的循环
for i in range(4):
nx=p[0]+dx[i]
ny=p[1]+dy[i]
#判断是否可以移动以及是否已经访问过(d[nx] [ny]!=INF即为已经访问过)
if 0<=nx<n and 0<=ny<m and maze[nx][ny]!='#' and d[nx][ny]==float('inf'):
d[nx][ny]=d[p[0]][p[1]]+1
#可以移动的话,则加入到队列,并且到该位置的距离确定为到p的距离+1
queue.append([nx,ny])
return d[gx][gy]
res=bfs()
print(res)
#print(d)