- 第一步写出队列,起始点,终点
- 深度优先搜索使用栈来实现
- 依次按照自己设定的顺序把走过的路入栈
- 判断走过的位置是否到达结尾
- 如果走到的位置为0说明为空,可走,并设定为2说明已走过
- 如果此时上下左右都没有路,就出栈,往回退
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, y + 1),
lambda x, y: (x + 1, y),
lambda x, y: (x, y - 1),
]
def maze_path(x1,y1,x2,y2):
stack=[]
stack.append((x1,y1))
maze[x1][y1]=2
while(len(stack)>0):
curnode=stack[-1]
if curnode[0] == x2 and curnode[1] ==y2:
for p in stack:
print(p)
return True
for dir in dirs:
nextnode=dir(curnode[0],curnode[1])
if maze[nextnode[0]][nextnode[1]]==0:
stack.append(nextnode)
maze[nextnode[0]][nextnode[1]]=2
break
else:
stack.pop()
else:
print("没有路")
return False
maze_path(1,1,8,8)