python 走迷宫返回路径
时间: 2023-10-11 08:07:12 浏览: 63
可以用深度优先搜索或广度优先搜索算法来解决这个问题。以下是一个基于深度优先搜索的示例代码:
```python
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]
]
# 用一个栈来保存访问过的路径
stack = [(0, 0)]
# 用一个字典来保存每个点的前驱节点
prev = {(0, 0): None}
# 用一个变量来标记是否已经找到出口
found = False
# 深度优先搜索
while stack:
x, y = stack.pop()
# 如果已经到达出口,跳出循环
if x == len(maze) - 1 and y == len(maze[0]) - 1:
found = True
break
# 遍历四个方向
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
nx, ny = x + dx, y + dy
# 如果下一步在迷宫内,并且没有访问过
if 0 <= nx < len(maze) and 0 <= ny < len(maze[0]) and maze[nx][ny] == 0 and (nx, ny) not in prev:
stack.append((nx, ny))
prev[(nx, ny)] = (x, y)
# 如果找到了出口,回溯路径
if found:
path = []
x, y = len(maze) - 1, len(maze[0]) - 1
while (x, y) != (0, 0):
path.append((x, y))
x, y = prev[(x, y)]
path.append((0, 0))
path.reverse()
print(path)
else:
print("No path found.")
```
输出结果为:`[(0, 0), (0, 1), (1, 1), (2, 1), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (3, 2), (3, 3), (3, 4), (4, 4)]`,表示从起点到出口的路径。
阅读全文