-
Notifications
You must be signed in to change notification settings - Fork 850
Expand file tree
/
Copy pathdijkstra.py
More file actions
44 lines (33 loc) · 1.21 KB
/
dijkstra.py
File metadata and controls
44 lines (33 loc) · 1.21 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
import heapq
def dijkstra(graph, start):
"""
Dijkstra's algorithm to find shortest paths from start node to all other nodes.
Parameters:
graph : dict - adjacency list {node: [(neighbor, weight), ...]}
start : starting node
Returns:
distances : dict - shortest distance from start to each node
"""
distances = {node: float('inf') for node in graph}
distances[start] = 0
priority_queue = [(0, start)] # (distance, node)
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node]:
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
# Example usage:
if __name__ == "__main__":
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)]
}
start_node = 'A'
print("Shortest distances:", dijkstra(graph, start_node))