以下是一个使用BFS算法解决迷宫问题并显示最短路径的示例代码:
from collections import deque
def find_shortest_path(maze, start, end):
rows = len(maze)
cols = len(maze[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = deque([(start, [])])
visited = set()
while queue:
(x, y), path = queue.popleft()
if (x, y) == end:
return path
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0 and (nx, ny) not in visited:
visited.add((nx, ny))
queue.append(((nx, ny), path + [(nx, ny)]))
return None
# 示例用法
maze = [
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0]
]
start = (0, 0)
end = (4, 4)
shortest_path = find_shortest_path(maze, start, end)
if shortest_path:
print("最短路径为:", shortest_path)
else:
print("没有找到最短路径")
该示例代码实现了一个find_shortest_path
函数,它使用BFS算法搜索从起点到终点的最短路径。迷宫是一个由0和1组成的二维数组,其中0表示可通行的路径,1表示墙壁。函数从起点开始,使用队列来保存待访问的节点,并通过一个集合来记录已访问过的节点。在每一步中,函数检查当前节点的四个相邻节点,如果相邻节点是可通行的且未被访问过,则将其添加到队列中,并更新路径。最后,如果找到了终点,则返回最短路径,否则返回None。
在示例用法中,我们定义了一个迷宫和起点、终点的坐标,并调用find_shortest_path
函数来计算最短路径。如果找到了最短路径,则打印出来,否则打印提示信息。