Python 迷宫寻路算法:广度优先搜索实现
以下是用 Python 语言实现广度优先遍历的迷宫寻路算法的示例代码:
from collections import deque
def find_path(maze):
start = (0, 0) # 起始位置
goal = (len(maze)-1, len(maze[0])-1) # 终点位置
queue = deque([(start, [])]) # 使用队列保存未探索的位置和路径
visited = set() # 使用集合保存已访问的位置
while queue:
position, path = queue.popleft()
x, y = position
if position == goal:
return path + [position] # 找到终点,返回路径
if position in visited:
continue # 如果位置已访问过,跳过
visited.add(position)
# 计算下一个可能的移动位置
moves = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
for move in moves:
new_x, new_y = move
if 0 <= new_x < len(maze) and 0 <= new_y < len(maze[0]) and maze[new_x][new_y] == 0:
queue.append((move, path + [position])) # 将新位置和路径加入队列
return None # 未找到路径
# 测试
maze = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 0]
]
path = find_path(maze)
if path:
print('找到路径: ', path)
else:
print('未找到路径')
代码解释:
- 数据结构: 二维数组表示迷宫,其中
0代表可通过的路径,1代表墙壁。 - 广度优先遍历: 算法使用
queue存储未探索的节点和当前路径,并使用visited集合记录已访问的节点。 - 寻找路径: 算法从起点开始,逐层探索周围可行位置,直到找到终点或所有节点都被访问。
希望以上代码能帮助你理解如何使用 Python 实现广度优先搜索算法解决迷宫寻路问题。如果你还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/QGn 著作权归作者所有。请勿转载和采集!