forked from qiwsir/algorithm
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra_algorithm.py
More file actions
Latest commit
51 lines (37 loc) · 1.66 KB
/
Copy pathdijkstra_algorithm.py
File metadata and controls
51 lines (37 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python
#coding:utf-8
"""
最短路径问题的Dijkstra算法
是由荷兰计算机科学家艾兹赫尔·戴克斯特拉提出。迪科斯彻算法使用了广度优先搜索解决非负权有向图的单源最短路径问题,算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。
这个算法的python实现途径很多,网上能够发现不少。这里推荐一个我在网上看到的,本来打算自己写,看了这个,决定自己不写了,因为他的已经太好了。
"""
# Dijkstra's algorithm for shortest paths
# David Eppstein, UC Irvine, 4 April 2002
# code source:http://www.algolist.com/code/python/Dijkstra%27s_algorithm
frompriodictimportpriorityDictionary
defDijkstra(G,start,end=None):
D= {} # dictionary of final distances
P= {} # dictionary of predecessors
Q=priorityDictionary() # est.dist. of non-final vert.
Q[start] =0
forvinQ:
D[v] =Q[v]
ifv==end: break
forwinG[v]:
vwLength=D[v] +G[v][w]
ifwinD:
ifvwLength<D[w]:
raiseValueError, "Dijkstra: found better path to already-final vertex"
elifwnotinQorvwLength<Q[w]:
Q[w] =vwLength
P[w] =v
return (D,P)
defshortestPath(G,start,end):
D,P=Dijkstra(G,start,end)
Path= []
while1:
Path.append(end)
ifend==start: break
end=P[end]
Path.reverse()
returnPath