广度优先查找之迷宫问题
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))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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训练数据并当服务器共享给他人