1 from collections import deque
2
3 maze = [
4 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
5 [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
6 [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
7 [1, 0, 0, 0, 0, 1, 1, 0, 0, 1],
8 [1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
9 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
10 [1, 0, 1, 0, 0, 0, 1, 0, 0, 1],
11 [1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
12 [1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
13 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
14 ]
15 dirs = [
16 lambda x, y: (x, y+1), # 右
17 lambda x, y: (x+1, y), # 下
18 lambda x, y: (x, y-1), # 左
19 lambda x, y: (x-1, y), # 上
20 ]
21
22
23 def print_maze_path(path):
24 print('迷宫的最短路径为')
25 real_path = []
26 cur_node = path[-1]
27 while cur_node[2] != -1:
28 real_path.append(cur_node[:2])
29 cur_node = path[cur_node[2]]
30 real_path.append(path[0][:2])
31 real_path.reverse()
32 print(real_path)
33
34
35 def maze_path_queue(start, end):
36 m_queue = deque()
37 m_queue.append((*start, -1))
38 path = []
39 maze[start[0]][start[1]] = 2
40 while len(m_queue) > 0:
41 cur_node = m_queue.popleft()
42 path.append(cur_node)
43 if path[-1][:2] == end:
44 print_maze_path(path)
45 return True
46 for dir in dirs:
47 next_node = dir(cur_node[0], cur_node[1])
48 if maze[next_node[0]][next_node[1]] == 0:
49 maze[next_node[0]][next_node[1]] = 2
50 m_queue.append((*next_node, len(path)-1))
51 else:
52 # 主要操作可用来调整path序列,介于问题的复杂度,不进行操作
53 pass
54 else:
55 print('不存在能出迷宫的路径')
56 return False
57
58
59 if __name__ == '__main__':
60 maze_path_queue((1, 1), (1, 8))