给出一个二维列表表示迷宫(0表示通道,1表示围墙)
设计算法,求一条走出迷宫的路径。
栈——深度优先搜索(DFS)
回溯法:从一个节点开始,任意找下一个能走的节点,当遇到走不通的节点时,退回上一个节点寻找其他方向是否能够走通。
使用栈存储当前路径。
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]
]
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)]
def maze_path(x1, y1, x2, y2):
stack = []
stack.append((x1, y1))
while len(stack) > 0:
curNode = stack[-1]
if curNode[0] == x2 and curNode[1] == y2:
print(stack)
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:
# maze[nextNode[0]][nextNode[1]] = 2
stack.pop()
else:
print("There is no way.")
return False
maze_path(1,1,8,8)
队列——广度优先搜索(BFS)
从一个节点开始,寻找所有接下来能够继续走的点,不断寻找直到找到出口。
使用队列存储当前正在考虑的节点。
from collections import deque
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]
]
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)]
def print_r(path):
curNode = path[-1]
realpath = []
while curNode[-1] != -1:
realpath.append(curNode[0:2])
curNode = path[curNode[-1]]
realpath.append(curNode[0:2])
realpath.reverse()
print(realpath)
def maze_path_queue(x1, y1, x2, y2):
queue = deque()
queue.append((x1, y1, -1))
path = []
while len(queue) > 0:
curNode = queue.pop()
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("There is no way.")
return False
maze_path_queue(1,1,8,8)