广度优先查找之迷宫问题

复制代码
 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))
复制代码

 

posted @   Avery_rainys  阅读(45)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示