BFS的python走迷宫
时间: 2023-10-31 09:07:31 浏览: 97
基于Python的迷宫设计
好的,以下是BFS的python走迷宫代码:
```python
from collections import deque
def bfs(maze, start, end):
queue = deque([start])
visited = set([start])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while queue:
x, y = queue.popleft()
if (x, y) == end:
return True
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < len(maze) and 0 <= new_y < len(maze[0]) and (new_x, new_y) not in visited and maze[new_x][new_y] == 0:
queue.append((new_x, new_y))
visited.add((new_x, new_y))
return False
maze = [[0, 1, 0, 0],
[0, 0, 0, 1],
[1, 1, 0, 0], [1, 1, 1, 0]]
start = (0, 0)
end = (3, 3)
print(bfs(maze, start, end))
```
输出结果为True,表示可以从起点走到终点。
阅读全文