以下代码来自网络,但是我不能写来源,因为写了来源网址,这里就不让我发出这篇文章。这不是逼着我剽窃吗?
#!/usr/bin/env python #coding:utf-8 # Dijkstra's algorithm for shortest paths # David Eppstein, UC Irvine, 4 April 2002 from priodict import priorityDictionary def Dijkstra(G,start,end=None): D = {} # dictionary of final distances P = {} # dictionary of predecessors Q = priorityDictionary() # est.dist. of non-final vert. Q[start] = 0 for v in Q: D[v] = Q[v] if v == end: break for w in G[v]: vwLength = D[v] + G[v][w] if w in D: if vwLength < D[w]: raise ValueError, "Dijkstra: found better path to already-final vertex" elif w not in Q or vwLength < Q[w]: Q[w] = vwLength P[w] = v return (D,P) def shortestPath(G,start,end): D,P = Dijkstra(G,start,end)
最短路径问题的Dijkstra算法,布布扣,bubuko.com
原文地址:http://blog.csdn.net/qiwsir/article/details/32899895