NowCoder最喜欢游乐场的迷宫游戏,他和小伙伴们比赛谁先走出迷宫。
现在把迷宫的地图给你,你能帮他算出最快走出迷宫需要多少步吗?
输入包含多组数据。
每组数据包含一个10*10,由“#”和“.”组成的迷宫。其中“#”代表墙;“.”代表通路。
入口在第一行第二列;出口在最后一行第九列。
从任意一个“.”点都能一步走到上下左右四个方向的“.”点。
对应每组数据,输出从入口到出口最短需要几步。
#.######## #........# #........# #........# #........# #........# #........# #........# #........# ########.# #.######## #........# ########.# #........# #.######## #........# ########.# #........# #.######.# ########.#
16 30
from collections import deque
def f(maze):
start = [0,1,0]
end = [9,8]
directions = [[1,0],[0,1],[-1,0],[0,-1]]
queue = deque()
visit = [[True]*len(maze[0]) for i in range(len(maze))]
queue.append(start)
visit[start[0]][start[1]] = False
while len(queue) > 0:
cur = queue.popleft()
if cur[0] == end[0] and cur[1] == end[1]:
return cur[2]
for i in range(4):
x = cur[0] + directions[i][0]
y = cur[1] + directions[i][1]
if x >=0 and x < len(maze) and y >= 0 and y < len(maze[0]) and maze[x][y] == '.' and visit[x][y]:
queue.append([x,y,cur[2]+1])
visit[x][y] = False
#解决输出为空的问题!
while True:
try:
maze = []
for i in range(10):
tmp = raw_input()
maze.append(tmp)
print f(maze)
except:
break