bfs算法python迷宫问题
时间: 2023-11-25 19:50:20 浏览: 98
以下是使用BFS算法解决Python迷宫问题的代码示例:
```python
from queue import Queue
# 定义迷宫地图
maze = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[0, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 0, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
# 定义四个方向
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# 定义BFS算法
def bfs(maze, start, end):
queue = Queue()
queue.put(start)
visited = set()
visited.add(start)
prev = dict()
while not queue.empty():
cur = queue.get()
if cur == end:
print_path(prev, start, end)
return
for direction in directions:
next_pos = (cur[0] + direction[0], cur[1] + direction[1])
if is_valid(maze, next_pos) and next_pos not in visited:
queue.put(next_pos)
visited.add(next_pos)
prev[next_pos] = cur
# 判断下一个位置是否合法
def is_valid(maze, pos):
if pos[0] < 0 or pos[0] >= len(maze) or pos[1] < 0 or pos[1] >= len(maze[0]):
return False
if maze[pos[0]][pos[1]] == 0:
return False
return True
# 输出路径
def print_path(prev, start, end):
ltmp = []
node = end
while node != start:
ltmp.append(node)
node = prev[node]
ltmp.append(start)
t_print(ltmp)
# 输出函数
def t_print(ltmp):
node = ltmp[-1]
ltmp_s = []
while node in prev:
ltmp_s.append(node)
node = prev[node]
ltmp_s.append(node)
ltmp_s.reverse()
for i in ltmp_s:
print(i)
# 测试
start = (1, 1)
end = (8, 8)
bfs(maze, start, end)
```
阅读全文