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, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
for i in maze:
print(i,end='\n')
# 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),
# ]
dirs=[ #左右上下
lambda x, y: (x - 1, y),
lambda x, y: (x, y + 1),
lambda x, y: (x + 1, y),
lambda x, y: (x, y - 1),
]
from collections import deque
def print_r(path):
curnode = path[-1] #取栈顶(终点) 是真实路径上的点
realpath=[]
while curnode[2] !=-1: #
realpath.append(curnode[0:2])
curnode=path[curnode[2]]
realpath.append(curnode[0:2]) #起点
realpath.reverse()
for node in realpath:
print(node)
def path_deque(x1,y1,x2,y2):
queue=deque()
queue.append((x1,y1,-1)) #-1表示放在起点开始
path = [] #放出栈头的元素
while len(queue) >0:
curnode =queue.popleft() #出栈头元素
path.append(curnode) #记录出栈的元素,
if curnode[0]==x2 and curnode[1]==y2:
#终点
print_r(path)
return True
for dir in dirs:
nextnode = dir(curnode[0],curnode[1])
if maze[nextnode[0]][nextnode[1]]==0:
queue.append((nextnode[0],nextnode[1],len(path)-1)) #后续节点进队,记录哪个节点带它来的
maze[nextnode[0]][nextnode[1]]=2
else:
print("没有错")
return False
path_deque(1,1,8,8)
队列-广度优先队列
最新推荐文章于 2024-09-15 22:31:42 发布