Dijkstra's shortest path
Pop the cheapest, skip stale, relax neighbors.
Edges have non-negative weights and you need the cheapest path from a source.
Trigger words
weighted graph
network delay
cheapest path
minimum effort
non-negative weights
connect all points + cost
import heapq
def shortest_distances(graph, start): # graph[node] = [(neighbor, weight), ...]
dist = {start: 0}
heap = [(0, start)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue # an older, longer entry
for neighbor, weight in graph[node]:
new_d = d + weight
if neighbor not in dist or new_d < dist[neighbor]:
dist[neighbor] = new_d
heapq.heappush(heap, (new_d, neighbor))
return distSpot it when
- 'Network delay time', 'cheapest path', 'minimum effort'.
- Weighted graph with no negative edges.
Remember
- The heap always gives the unfinished node with the smallest known distance.
- Skipping stale entries keeps the loop correct without a decrease-key operation.
How problems bend it
- Grid with costs (swim in rising water): Nodes are cells; the cost of a path is its largest height, so push max(d, height).
- At most k stops: Use Bellman-Ford style rounds instead: relax all edges k + 1 times from a copy of the distances.
- Minimum spanning tree (Prim): Same heap loop, but push the single edge's cost instead of the path total, and add each node to the tree the first time it is popped.

