-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstras.py
42 lines (29 loc) · 1009 Bytes
/
dijkstras.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
from functools import reduce
def dijkstras(weighted_graph,src,dst):
vertices = set()
dist = {}
prev = {}
# add all vertices to set
for vertex in weighted_graph.vertices:
vertices.add(vertex)
dist[vertex] = float('inf')
prev[vertex] = None
dist[src] = 0
while vertices:
min_dist_node = min(list(filter(lambda x: x[0] in vertices,dist.items())),key=lambda x: x[1])[0]
if min_dist_node == dst:
break
vertices.remove(min_dist_node)
for neighbor in weighted_graph.vertices[min_dist_node].adjacent:
distance = weighted_graph.vertices[min_dist_node].adjacent[neighbor]
if distance < dist[neighbor]:
dist[neighbor] = distance
prev[neighbor] = min_dist_node
# trace back from dst
path = []
current = dst
while prev[current]:
path.append(current)
current = prev[current]
path.append(current)
return path[::-1]