-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortest_path.py
More file actions
35 lines (27 loc) · 1.02 KB
/
shortest_path.py
File metadata and controls
35 lines (27 loc) · 1.02 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
import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
entry_lookup = {}
pq = []
for vertex, distance in distances.items():
entry = [distance, vertex]
entry_lookup[vertex] = entry
heapq.heappush(pq, entry)
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
for neighbor, neighbor_distance in graph[current_vertex].items():
distance = distances[current_vertex] + neighbor_distance
if distance < distances[neighbor]:
distances[neighbor] = distance
entry_lookup[neighbor][0] = distance
return distances
example_graph = {
'U': {'V': 2, 'W': 5, 'X': 1},
'V': {'U': 2, 'X': 2, 'W': 3},
'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5},
'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1},
'Y': {'X': 1, 'W': 1, 'Z': 1},
'Z': {'W': 5, 'Y': 1},
}
print(calculate_distances(example_graph, 'X'))