-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA2.html
More file actions
45 lines (36 loc) · 1.33 KB
/
A2.html
File metadata and controls
45 lines (36 loc) · 1.33 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
import heapq
def dijkstra(graph, start,end) :
# Priority queue to store (distance, node)
queue = [(0, start)]
distances = {node: float('inf') for node in graph}
distances[start] = 0
previous_nodes = {node: None for node in graph}
while queue:
current_distance, current_node = heapq.heappop(queue)
# If we reached the destination, reconstruct the path
if current_node == end:
path = []
while current_node:
path.append(current_node)
current_node = previous_nodes[current_node]
return path[::-1], distances[end]
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
# If found shorter path to neighbor
if distance < distances[neighbor]:
distances[neighbor] = distance
previous_nodes[neighbor] = current_node
heapq.heappush(queue, (distance, neighbor))
return None, float('inf')
# Example usage:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
path, distance = dijkstra(graph, 'A', 'D')
print(f"Shortest path: {path}")
print(f"Distance: {distance}")