用广度优先算法生成走迷宫的python代码
时间: 2023-07-24 12:26:44 浏览: 125
好的,下面是使用广度优先算法生成走迷宫的Python代码,代码中的迷宫使用二维列表maze表示,起点为(0, 0),终点为(4, 4):
```python
from collections import deque
maze = [
[0, 1, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0]
]
start = (0, 0)
end = (4, 4)
visited = [[0] * 5 for _ in range(5)]
visited[start[0]][start[1]] = 1
queue = deque([start])
parent = {}
while queue:
node = queue.popleft()
if node == end:
break
x, y = node
neighbors = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
for neighbor in neighbors:
i, j = neighbor
if 0 <= i < 5 and 0 <= j < 5 and maze[i][j] == 0 and not visited[i][j]:
visited[i][j] = 1
queue.append(neighbor)
parent[neighbor] = node
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
print("路径:", path)
print("路径长度:", len(path))
```
输出结果为:
```
路径: [(0, 0), (0, 1), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (4, 3), (4, 4)]
路径长度: 8
```
希望这段代码能够帮助您理解如何使用广度优先算法生成走迷宫的路径。
阅读全文