迷宫自动寻路python
时间: 2023-11-24 17:53:16 浏览: 155
基于Python实现迷宫求解【100011880】
以下是一个基于深度优先搜索算法的迷宫自动寻路Python代码,你可以根据自己的需要进行修改和调试:
```python
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 dfs(x1, y1, x2, y2):
stack = []
stack.append((x1, y1))
while len(stack) > 0:
cur_node = stack[-1]
if cur_node[0] == x2 and cur_node[1] == y2:
for p in stack:
print(p)
return True
for dir in dirs:
next_node = dir(cur_node[0], cur_node[1])
if maze[next_node[0]][next_node[1]] == 0:
stack.append(next_node)
maze[next_node[0]][next_node[1]] = -1
break
else:
maze[cur_node[0]][cur_node[1]] = -1
stack.pop()
else:
print("No path found.")
return False
dfs(1, 1, 8, 8)
```
这段代码实现了从起点(1,1)到终点(8,8)的自动寻路,其中1代表墙壁,0代表可走的点,-1代表已经走过的点。你可以根据自己的需要修改迷宫地图和起点终点坐标。
阅读全文