-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
57 lines (48 loc) · 1.28 KB
/
dijkstra.py
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
51
52
53
54
55
56
57
graph = {
'a': [('b', 2), ('c', 1)],
'b': [('c', 1)],
'c': [('a', 9), ('d', 8), ('e', 2)],
'd': [('a', 3)],
'e': [('d', 3)]
}
source = 'c'
def find_min(relaxers, unexplored):
min_vertex = None
min_value = float('inf')
for vertex in relaxers:
if vertex not in unexplored:
continue
if relaxers[vertex] < min_value:
min_value = relaxers[vertex]
min_vertex = vertex
return min_vertex
paths = {}
relaxers = {}
unexplored = []
for vertex in graph:
unexplored.append(vertex)
relaxers[vertex] = float('inf')
paths[vertex] = []
relaxers[source] = 0
while len(unexplored) > 0:
min_vertex = find_min(relaxers, unexplored)
min_vertex_dist = relaxers[min_vertex]
paths[min_vertex] = source
source = min_vertex
unexplored.remove(min_vertex)
adj_list = graph[min_vertex]
for (adj_vertex, adj_vertex_dist) in adj_list:
if min_vertex_dist + adj_vertex_dist < relaxers[adj_vertex]:
relaxers[adj_vertex] = min_vertex_dist + adj_vertex_dist
print paths
print relaxers
dest = 'b'
source = 'c'
path = []
print 'Path cost:', relaxers[dest]
while (dest != source):
path.append(dest)
dest = paths[dest]
path.append(source)
path.reverse()
print 'Path:', path