Goal
Find the shortest path from a source node to all other nodes in a graph with non-negative edge weights.
Setup
Graph can be directed or undirected. Edge weights must be nonnegative. Let: , where and (s is the starting node) We use two key data structures:
dist[]is a distance array wheredist[v] = shortest distance from source to v. We initialize this to infinity for all nodes exceptdist[s] = 0- Priority Queue / Min Heap: always pick the unvisited node with the smallest tentative distance
Algorithm
- Initialize
dist[v] = infinityfor all nodes ; setdist[s]=0- Insert all nodes into a min-priority queue with their distances
- while the queue is not empty:
- Extract the node with minimum
dist[u]- For each neighbor of :
- If going through improves the distance to :
- Update the priority queue with new
dist[v]4.dist[]now contains the shortest distances fromsto every other node.
import heapq
from collections import defaultdict
def dijkstra(graph, start):
dist = {node: float('inf') for node in graph}
dist[start] = 0
# Min-heap: (distance, node)
pq = [(0, start)]
while pq:
current_dist, u = heapq.heappop(pq)
# Skip if we found a better path already
if current_dist > dist[u]:
continue
for v, weight in graph[u]:
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(pq, (dist[v], v))
return dist