Skip to content

Commit 1419cd6

Browse files
committed
最短路径之Dijkstra算法
1 parent 50e3372 commit 1419cd6

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed

dijkstra_algorithm.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#问题
2+
3+
最短路径问题的Dijkstra算法
4+
5+
是由荷兰计算机科学家艾兹赫尔·戴克斯特拉提出。迪科斯彻算法使用了广度优先搜索解决非负权有向图的单源最短路径问题,算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。
6+
7+
这个算法的python实现途径很多,网上能够发现不少。这里推荐一个我在网上看到的,本来打算自己写,看了这个,决定自己不写了,因为他的已经太好了。
8+
9+
#解决(Python)
10+
11+
#!/usr/bin/env python
12+
#coding:utf-8
13+
14+
# Dijkstra's algorithm for shortest paths
15+
# David Eppstein, UC Irvine, 4 April 2002
16+
# code source:http://www.algolist.com/code/python/Dijkstra%27s_algorithm
17+
18+
from priodict import priorityDictionary
19+
20+
def Dijkstra(G,start,end=None):
21+
D = {} # dictionary of final distances
22+
P = {} # dictionary of predecessors
23+
Q = priorityDictionary() # est.dist. of non-final vert.
24+
Q[start] = 0
25+
26+
for v in Q:
27+
D[v] = Q[v]
28+
29+
if v == end: break
30+
31+
for w in G[v]:
32+
vwLength = D[v] + G[v][w]
33+
if w in D:
34+
if vwLength < D[w]:
35+
raise ValueError, "Dijkstra: found better path to already-final vertex"
36+
37+
elif w not in Q or vwLength < Q[w]:
38+
Q[w] = vwLength
39+
P[w] = v
40+
41+
return (D,P)
42+
43+
def shortestPath(G,start,end):
44+
D,P = Dijkstra(G,start,end)
45+
Path = []
46+
while 1:
47+
48+
Path.append(end)
49+
if end == start: break
50+
end = P[end]
51+
52+
Path.reverse()
53+
return Path
54+

dijkstra_algorithm.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python
2+
#coding:utf-8
3+
"""
4+
最短路径问题的Dijkstra算法
5+
6+
是由荷兰计算机科学家艾兹赫尔·戴克斯特拉提出。迪科斯彻算法使用了广度优先搜索解决非负权有向图的单源最短路径问题,算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。
7+
8+
这个算法的python实现途径很多,网上能够发现不少。这里推荐一个我在网上看到的,本来打算自己写,看了这个,决定自己不写了,因为他的已经太好了。
9+
"""
10+
11+
# Dijkstra's algorithm for shortest paths
12+
# David Eppstein, UC Irvine, 4 April 2002
13+
# code source:http://www.algolist.com/code/python/Dijkstra%27s_algorithm
14+
15+
from priodict import priorityDictionary
16+
17+
def Dijkstra(G,start,end=None):
18+
D = {} # dictionary of final distances
19+
P = {} # dictionary of predecessors
20+
Q = priorityDictionary() # est.dist. of non-final vert.
21+
Q[start] = 0
22+
23+
for v in Q:
24+
D[v] = Q[v]
25+
26+
if v == end: break
27+
28+
for w in G[v]:
29+
vwLength = D[v] + G[v][w]
30+
if w in D:
31+
if vwLength < D[w]:
32+
raise ValueError, "Dijkstra: found better path to already-final vertex"
33+
34+
elif w not in Q or vwLength < Q[w]:
35+
Q[w] = vwLength
36+
P[w] = v
37+
38+
return (D,P)
39+
40+
def shortestPath(G,start,end):
41+
D,P = Dijkstra(G,start,end)
42+
Path = []
43+
while 1:
44+
45+
Path.append(end)
46+
if end == start: break
47+
end = P[end]
48+
49+
Path.reverse()
50+
return Path
51+

0 commit comments

Comments
 (0)