栈应用——深度优先搜索
思路:上下左右,不行就回退,看别的岔路,能走的点放到栈里走过的路标记为墙(走回头路没有意义)
最后栈空表示没有通路
特点:代码简单,但搜索路径并不一定是min
算法实现:
maze=[
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,1],
[1,0,1,0,1,1,0,1,0,1],
[1,0,1,0,0,1,0,1,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,1,0,0,1,1,0,0,1],
[1,0,1,1,0,0,0,0,0,1],
[1,0,0,0,0,1,1,1,0,1],
[1,1,1,1,1,1,1,1,1,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),
]
def maze_path(x1,y1,x2,y2):
stack=[]
stack.append((x1,y1))
while len(stack)>0:
curxy=stack[-1]#当前的节点
if curxy[0]==x2 and curxy[1]==y2:
#走到终点了
for i in stack:
print(i)
return True
#x,y四个方向:x-1,y;x+1,y;x,y+1;x,y-1;
for dirc in dirs:
nextxy = dirc(curxy[0],curxy[1])
#如果下一个节点能走
if maze[nextxy[0]][nextxy[1]]==0:
stack.append(nextxy)
maze[nextxy[0]][nextxy[1]]=1
#标记为已经走过
break
else :
maze[nextxy[0]][nextxy[1]]=1
stack.pop()
else:
print("I've tried my best but there's no way!")
return False
maze_path(1,1,8,8)
队列应用——广度优先搜索
每一次需要记录几号位让它来的,队空表示没有路
最后再回溯寻找最短路径
测试段程序
测试段结果 :每一段表示这一次for循环通过第一项找到了最后新增几项的值,后面把第一项删掉
但二维的表帧path并不是好方法,记录上个点在一维数组中的下标,才是越过鸿沟天堑的法宝,实现如下:
from collections import deque
maze=[
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,1],
[1,0,1,0,1,1,0,1,0,1],
[1,0,1,0,0,1,0,1,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,1,0,0,1,1,0,0,1],
[1,0,1,1,0,0,0,0,0,1],
[1,0,0,0,0,1,1,1,0,1],
[1,1,1,1,1,1,1,1,1,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),
]
path=[]
def maze_path_queue(x1,y1,x2,y2):
queue = deque()
queue.append((x1,y1,-1))
while len(queue)>0:
curxy=queue.popleft()
path.append(curxy)
if curxy[0]==x2 and curxy[1]==y2:
#终点
backtrack(path)
return True
for dirc in dirs:
nextxy=dirc(curxy[0],curxy[1])
if maze[nextxy[0]][nextxy[1]]==0:
queue.append((nextxy[0],nextxy[1],len(path)-1))
#后续节点进队,记录哪个节点带他来的
maze[nextxy[0]][nextxy[1]]=1
#标记为已经走过
else :
print("I've tried my best but there's no way!")
return False
def backtrack(path):
curxy=path[-1]
realpath=[]
while curxy[2] != -1:
realpath.append(curxy[0:2])
curxy=path[curxy[2]]
realpath.append(curxy[0:2])#起点
realpath.reverse()
for j in realpath:
print(j)
maze_path_queue(1,1,8,8)
部分图片参考自b站IT编程界的扛把子的python算法学习视频,本文仅供个人学习使用,特此声明