-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstrasAlgorithm.py
More file actions
35 lines (25 loc) · 899 Bytes
/
DijkstrasAlgorithm.py
File metadata and controls
35 lines (25 loc) · 899 Bytes
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
from heapq import heappop, heappush
from math import inf
graph = {
'A': [('B', 10), ('C', 3)],
'C': [('D', 2)],
'D': [('E', 10)],
'E': [('A', 7)],
'B': [('C', 3), ('D', 2)]
}
def dijkstras(graph, start):
distances = {}
for vertex in graph:
distances[vertex] = inf
distances[start] = 0
vertices_to_explore = [(0, start)]
while vertices_to_explore:
current_distance, current_vertex = heappop(vertices_to_explore)
for neighbor, edge_weight in graph[current_vertex]:
new_distance = current_distance + edge_weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heappush(vertices_to_explore, (new_distance, neighbor))
return distances
distances_from_d = dijkstras(graph, 'D')
print("\n\nShortest Distances: {0}".format(distances_from_d))