python dijkstra 最短路算法示意代码

 

def dijkstra(graph,from_node,to_node):
    q,seen = [(0,[])],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,"5"))
print(dijkstra(air_lines,"4","5","1"))
print(dijkstra(air_lines,"10","10"))

"""
(3000,[‘1‘,‘3‘,‘4‘])
(3000,‘2‘,‘5‘])
(500,[‘4‘,‘5‘])
(-1,[])
(0,[‘1‘])
(0,[‘10‘])
"""

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...