这么简单一个算法,懒得花时间去自己实现,然后就想在网上搜搜看是否有现成可用的。谁知试了几个,真头疼:写得真是太好(垃)用(圾)了。不是没有注释,就是不规范看起来巨不爽,更甚bug满天飞根本不能执行。也怪自己懒,算了不抱怨了,因为下边我贴出的例子也是基于GitHub上一个写得较为顺眼的例子,然后自己包了一下,并解析了一下原作的返回内容,使得它符合我的需求:输入一个src-dst pair,返回他们之间的 distance 与 shortest path。废话不多说,有图有真相:可以运行。需要的拿走用就是了。
====== A. Code: (The dijkstra_raw(...) is the borrowed function, the dijkstra(...) is my design.)
from collections import defaultdict
from heapq import *
def dijkstra_raw(edges, from_node, to_node):
g = defaultdict(list)
for l,r,c in edges:
g[l].append((c,r))
q, seen = [(0,from_node,())], set()
while q:
(cost,v1,path) = heappop(q)
if v1 not in seen:
seen.add(v1)
path = (v1,