python dijkstra 最短路算法示意代码
2024-10-20 11:36:15
def dijkstra(graph, from_node, to_node):
q, seen = [(0, from_node, [])], set()
while q:
cost, node, path = heappop(q)
seen.add(node)
path = path+[node]
if node == to_node:
return cost,path
for adj_node, c in graph.get(node, {}).items():
if adj_node not in seen:
heappush(q, (cost+c, adj_node, path))
return -1,[] air_lines = {"1":{"2":2000, "3":2000, "4":4000, "5": 4500}, "2":{"5": 1000}, "3":{"4": 1000}, "4":{"5": 500}} print(dijkstra(air_lines, "1", "4"))
print(dijkstra(air_lines, "1", "5"))
print(dijkstra(air_lines, "4", "5"))
print(dijkstra(air_lines, "5", "4"))
print(dijkstra(air_lines, "1", "1"))
print(dijkstra(air_lines, "10", "10")) """
(3000, ['1', '3', '4'])
(3000, ['1', '2', '5'])
(500, ['4', '5'])
(-1, [])
(0, ['1'])
(0, ['10'])
"""
最新文章
- C# Struct结构体里数组长度的指定
- shell 脚本编程概述
- 改变DataGrid某一行和单元格的颜色
- 使用WebView视图显示网页-----迷你浏览器
- android中string.xml引起的常见编译错误
- 关于asp:login控件和验证码的问题?(转)
- 在SQL Server Management Studio中可以运行作业但是用T-SQL运行则失败
- centos7 搭建elk
- MySQL数据库面试
- iptables snat和dnat
- asp.net core系列 28 EF模型配置(字段,构造函数,拥有实体类型)
- 关于新写的js在浏览器f12的时候看不到解决办法
- mongo 让字段自增或自减
- ACM-ICPC 2018 南京赛区网络预赛 J题Sum(线性筛素数)
- ArcGIS for qml -设置地图和视域中心
- 反射-Emit
- 私有仓库GitLab快速入门篇
- 第二篇:Jmeter功能概要
- bootstrapTable刷新当前页码不变和从第一页开始查询
- Angularjs 首次加载显示{{}}