-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstras-Shortest-Path-Algorithm.py
More file actions
48 lines (38 loc) · 1.13 KB
/
Copy pathDijkstras-Shortest-Path-Algorithm.py
File metadata and controls
48 lines (38 loc) · 1.13 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
36
37
38
39
40
41
42
43
44
45
46
47
48
import heapq
import time
def dijkstra(graph, start, end):
pq = [(0, start)]
dist = {node: float('inf') for node in graph}
prev = {node: None for node in graph}
dist[start] = 0
while pq:
current_dist, u = heapq.heappop(pq)
if u == end:
break
if current_dist > dist[u]:
continue
for v, weight in graph[u]:
new_dist = current_dist + weight
if new_dist < dist[v]:
dist[v] = new_dist
prev[v] = u
heapq.heappush(pq, (new_dist, v))
path = []
node = end
while node:
path.append(node)
node = prev[node]
return path[::-1], dist[end]
graph = {
'A': [('B', 4), ('C', 2)],
'B': [('A', 4), ('C', 1), ('D', 5)],
'C': [('A', 2), ('B', 1), ('D', 8), ('E', 10)],
'D': [('B', 5), ('C', 8), ('E', 2)],
'E': [('C', 10), ('D', 2)]
}
start_time = time.perf_counter()
path, distance = dijkstra(graph, 'A', 'E')
end_time = time.perf_counter()
print("Shortest Path:", path)
print("Total Distance:", distance)
print(f"Execution Time: {end_time - start_time:.6f} seconds")