maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,1,0,0,1],
[1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,1,0,1],
[1,1,0,0,0,0,0,1,0,1],
[1,1,1,1,1,1,1,1,1,1]
]
dirs = [
lambda x, y: (x + 1, y),
lambda x, y: (x - 1, y),
lambda x, y: (x, y + 1),
lambda x, y: (x, y - 1),
]
from collections import deque
def maze_find(x1, y1, x2, y2):
stack = deque()
stack.append((x1, y1))
while len(stack) > 0:
curNode = stack[-1]
if curNode[0] == x2 and curNode[1] == y2:
for p in stack:
print(p)
return True
for i in dirs:
nextNode = i(*curNode)
if maze[nextNode[0]][nextNode[1]] == 0:
stack.append(nextNode)
maze[nextNode[0]][nextNode[1]] = -1
break
else:
maze[curNode[0]][curNode[1]] = -1
stack.pop()
print('没有找到出口')
return False
#maze_find(1, 1, 8, 8)
def r_path(path):
curNode = path.pop()
rpath = []
while curNode[2] != -1:
rpath.append((curNode[0:2]))
curNode = path[curNode[2]]
return reversed(rpath)
def maze_q(x1, y1, x2, y2):
stack = deque()#建立一个队列
stack.append((x1, y1, -1))#初始化第一个起点
rpath = [] #结果路径
while len(stack) > 0: #当有队列存在循环
curNode = stack.popleft()#当前队列的第一个位置为当前位置
rpath.append(curNode)
for i in dirs:
nextNode = i(curNode[0], curNode[1])
#print(nextNode)
if nextNode[0] == x2 and nextNode[1] == y2:
print('开始走迷宫:')
print('起点位置:', (x1, y1))
for i in r_path(rpath):
print('途径位置:', i)
print('终点位置:', (x2, y2))
return True
if maze[nextNode[0]][nextNode[1]] == 0:
stack.append((nextNode[0], nextNode[1], len(rpath)-1))
maze[nextNode[0]][nextNode[1]] = -1
print('没有找到出口')
return False
maze_q(1, 1, 8, 8)
给你看一下我之前写的迷宫代码,基本上的思路就是先确定可以走的方向上下左右,然后每次走玩判断是不是到达终点,并记录该点已经走过。因为题目是全英文的,实在是看的头大。。。所以发一下自己之前写的吧