Skip to the content.

15. Dijkstra’s Shortest Path

Back to the index

Shortest paths from one source in a graph with non-negative edge weights. Always expand the closest unfinished node, using a min-heap.

How it works

Keep a best-known distance for every node (start: 0, others: infinity) and a min-heap of (distance, node) pairs. Repeatedly pop the smallest. Relax each outgoing edge: if going through this node gives a shorter distance to a neighbor, record it and push the new pair.

The heap may hold outdated (stale) entries for a node whose distance has since improved. Instead of deleting them, skip any popped entry whose distance is larger than the best known one. Negative edge weights break the algorithm; use Bellman-Ford for those.

Diagram

graph LR
    A -->|4| B
    A -->|1| C
    B -->|1| D
    C -->|2| B
    C -->|5| D
    D -->|3| E

Step-by-step trace

Input: Directed graph shown above. Shortest distances from A.

Step Pop (dist, node) Relaxations dist A dist B dist C dist D dist E Heap after
1 (0, A) B: inf -> 4; C: inf -> 1 0 4 1 inf inf (1, C), (4, B)
2 (1, C) B: 4 -> 3; D: inf -> 6 0 3 1 6 inf (3, B), (4, B), (6, D)
3 (3, B) D: 6 -> 4 0 3 1 4 inf (4, B), (4, D), (6, D)
4 (4, B) stale (best is 3), skip 0 3 1 4 inf (4, D), (6, D)
5 (4, D) E: inf -> 7 0 3 1 4 7 (6, D), (7, E)
6 (6, D) stale (best is 4), skip 0 3 1 4 7 (7, E)
7 (7, E) no edges 0 3 1 4 7 empty

Result: Final distances: A=0, B=3, C=1, D=4, E=7. Note step 4: the old entry (4, B) is stale because B was improved to 3 via C.

Complexity

Operation Time Space
Dijkstra with a binary heap O((V + E) log V) O(V + E)
BFS when all weights are 1 O(V + E) O(V)

Python reference implementation

def dijkstra(graph, source):
    """graph: {node: [(neighbor, weight), ...]} with non-negative weights."""
    dist = {source: 0}
    heap = [(0, source)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue                      # stale entry, a shorter path was found
        for nb, w in graph[node]:
            nd = d + w
            if nd < dist.get(nb, float("inf")):
                dist[nb] = nd
                heapq.heappush(heap, (nd, nb))
    return dist

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Graphs: Depth-First Search (DFS) Next: Topological Sort (Kahn’s Algorithm)