
python实现BFS算法(广度优先搜索)输出最短路径
发布日期:2021-05-10 14:50:22
浏览次数:19
分类:精选文章
本文共 2407 字,大约阅读时间需要 8 分钟。
���������������������������
��������������������������������������������� using BFS algorithm
���������BFS���������������������������������������������������������������������������������������������������������������������������������������������������BFS���������������������������������������������������������������������������������������������������������������������������
������������������������������a������������������������g���������������������
���������������������
from collections import deque# ������������������maps = dict()maps['a'] = ['b', 'c']maps['b'] = ['e']maps['c'] = ['d', 'f']maps['d'] = ['e']maps['f'] = ['e']maps['e'] = ['g']maps['g'] = []maps['h'] = []# ������������������start = 'a'finish = 'g'# ��������������� ���������������������my_deque = deque()my_deque += maps[start]# ������������������������searched = []# ������������������parents = dict()# ���������������������������������������������parents[start] = None# ���������������������������������������������path = [finish]while my_deque: current = my_deque.popleft() if current not in searched: if current == finish: # ������������������ temp = [] current_path = [current] if parents[current] is not None: temp.append(parents[current]) current_path.insert(0, parents[current]) while True: if len(temp) == 0: break next_node = parents.get(temp[-1], None) if next_node is None: if temp: temp.insert(0, start) break if next_node == start: temp.insert(0, start) break temp.insert(0, next_node) current_path.insert(0, next_node) path.reverse() print("���������������������������������������" + ' -> '.join(path)) break else: # ������������������������������������ my_deque += maps.get(current, []) # ��������������� for neighbor in maps.get(current, []): if neighbor not in parents and neighbor != current: parents[neighbor] = current searched.append(current)
���������������
���������������������������������������a -> b -> e -> g
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月26日 12时42分50秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
2021-05-09
httprunner学习23-加解密
2021-05-09
jenkins学习13-凭据管理(删除多余的凭据)
2021-05-09
有道云笔记 同步到我的博客园
2021-05-09
阿里云“网红"运维工程师白金:做一个平凡的圆梦人
2021-05-09
AnalyticDB for PostgreSQL 6.0 新特性介绍
2021-05-09
Alibaba Cloud Linux 2 LTS 正式发布,提供更高性能和更多保障!
2021-05-09
李笑来必读书籍整理
2021-05-09
vue书籍整理
2021-05-09
记Java中有关内存的简单认识
2021-05-09
Mybatis配置解析
2021-05-09
http头部 Expect
2021-05-09
Hadoop(十六)之使用Combiner优化MapReduce
2021-05-09
C#实现outlook自动签名
2021-05-09
《机器学习Python实现_10_06_集成学习_boosting_gbdt分类实现》
2021-05-09
CoreCLR源码探索(八) JIT的工作原理(详解篇)
2021-05-09
使用promise封装wx:requset()
2021-05-09
stm32h743iit6 cubmex 配置QSPI w25128模式问题
2021-05-09
让nginx支持文件上传的几种模式
2021-05-09