11. Dijkstra's Shortest Path

The algorithm that powers every map application

You open a maps app, type in a destination, and within a fraction of a second it draws the fastest route across an entire city. Behind the scenes, the road network is a weighted graph — intersections are nodes, roads are edges, and travel times are weights. The algorithm that finds the shortest path through this graph was invented by Edsger Dijkstra in 1956, scribbled on a cafe napkin in about twenty minutes.

It remains one of the most important algorithms in computer science — elegant, efficient, and everywhere.

The Problem

Given a weighted graph with non-negative edge weights and a source node, find the shortest path from the source to every other node in the graph. The "shortest" path is the one whose edge weights sum to the smallest total.

Dijkstra's Insight

If you always expand the closest unvisited node — the one with the smallest known distance from the source — then by the time you visit a node, you've already found the shortest path to it. No future path through other nodes can beat it, because all edge weights are non-negative.

This greedy strategy works because adding more edges to a path can only make it longer (or keep it the same), never shorter.

A Simple Example

A 6-node weighted graph

        2         1
   A ------→ B ------→ D
   |         |         ↑
 6 |       3 |         | 1
   ↓         ↓         |
   C ------→ E ------→ F
        5         2

Source: A. Find the shortest path from A to every other node.

Let's trace Dijkstra's algorithm step by step.

The Algorithm Step by Step

  1. Initialize

    Set the distance to the source to 0 and all other distances to ∞. Mark all nodes as unvisited. Add the source to the priority queue.

  2. Pick the closest unvisited node

    Extract the node with the smallest distance from the priority queue. Mark it as visited.

  3. Relax its neighbors

    For each unvisited neighbor, compute the distance through the current node. If this new distance is smaller than the previously known distance, update it and add/update the neighbor in the priority queue.

  4. Repeat

    Go back to step 2 until all reachable nodes have been visited (or the priority queue is empty).

Worked Example

Using the 6-node graph above, starting from A:

Step-by-step execution

Initial state:
  dist = { A:0, B:∞, C:∞, D:∞, E:∞, F:∞ }
  prev = { A:-, B:-, C:-, D:-, E:-, F:- }
  PQ   = [(A, 0)]

Step 1 — Visit A (dist=0): Relax A→B: 0+2=2 < ∞ → update B to 2 (prev=A) Relax A→C: 0+6=6 < ∞ → update C to 6 (prev=A) dist = { A:0, B:2, C:6, D:∞, E:∞, F:∞ } PQ = [(B, 2), (C, 6)]

Step 2 — Visit B (dist=2): Relax B→D: 2+1=3 < ∞ → update D to 3 (prev=B) Relax B→E: 2+3=5 < ∞ → update E to 5 (prev=B) dist = { A:0, B:2, C:6, D:3, E:5, F:∞ } PQ = [(D, 3), (E, 5), (C, 6)]

Step 3 — Visit D (dist=3): No outgoing unvisited neighbors. dist = { A:0, B:2, C:6, D:3, E:5, F:∞ } PQ = [(E, 5), (C, 6)]

Step 4 — Visit E (dist=5): Relax E→F: 5+2=7 < ∞ → update F to 7 (prev=E) dist = { A:0, B:2, C:6, D:3, E:5, F:7 } PQ = [(C, 6), (F, 7)]

Step 5 — Visit C (dist=6): Relax C→E: 6+5=11 > 5 → no update (E already has shorter path) dist = { A:0, B:2, C:6, D:3, E:5, F:7 } PQ = [(F, 7)]

Step 6 — Visit F (dist=7): Relax F→D: 7+1=8 > 3 → no update (D already has shorter path) dist = { A:0, B:2, C:6, D:3, E:5, F:7 } PQ = [] — done!

Reconstructing paths using the predecessor array

prev = { A:-, B:A, C:A, D:B, E:B, F:E }

Path to D: D ← B ← A → A → B → D (cost 3) Path to E: E ← B ← A → A → B → E (cost 5) Path to F: F ← E ← B ← A → A → B → E → F (cost 7) Path to C: C ← A → A → C (cost 6)

Why Negative Weights Break It

Dijkstra's correctness depends on a simple invariant: once a node is visited, its distance is final. This breaks when edges can have negative weights, because a longer path through more edges might end up cheaper.

A concrete counterexample

      1         10
  A ------→ B ------→ C
  |                    ↑
  |         -20        |
  +--------→ D -------→+
       5          1

Source: A. Dijkstra visits B first (dist=1), then goes to C via B with cost 11. It marks C as visited. But the true shortest path is A→D→C with cost 5+1=6... except A→D costs 5, and by the time we discover D, we've already finalized B at distance 1.

Worse: with the -20 edge, the path A→D has cost 5, but A→B→D doesn't exist here. The negative edge means a detour through D could yield a shorter total — but Dijkstra already committed to C's distance and won't reconsider it.

Bottom line: with negative weights, visiting a node early doesn't guarantee you've found the shortest path to it. The greedy assumption fails.

Pseudocode

function dijkstra(graph, source):
    dist = {}
    prev = {}
    visited = {}
    pq = new MinPriorityQueue()

    for each node v in graph:
        dist[v] = ∞
        prev[v] = null
    dist[source] = 0
    pq.insert(source, 0)

    while pq is not empty:
        u = pq.extractMin()
        if visited[u]: continue
        visited[u] = true

        for each neighbor v of u with weight w:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                prev[v] = u
                pq.insert(v, dist[v])

    return dist, prev

The "Lazy" Priority Queue Trick

Instead of updating a node's priority in the queue (which is expensive with a basic binary heap), we simply insert a new entry. When we extract a node that's already been visited, we skip it. This is simpler to implement and has the same asymptotic complexity.

Priority Queue Implementation

The efficiency of Dijkstra's algorithm depends entirely on the priority queue. The two critical operations are insert and extract-min.

Priority Queue Insert Extract-Min Total Complexity
Unsorted array O(1) O(V) O(V² + E)
Binary heap O(log V) O(log V) O((V + E) log V)
Fibonacci heap O(1) amortized O(log V) amortized O(V log V + E)

For sparse graphs (E ≈ V), the binary heap version is much faster than the array version. For dense graphs (E ≈ V²), the simple array version is competitive because the V² term dominates anyway.

Reconstructing the Actual Path

Dijkstra's algorithm computes shortest distances, but to recover the actual path, we maintain a predecessor array. Every time we relax an edge u → v, we record prev[v] = u.

function getPath(prev, target):
    path = []
    node = target
    while node is not null:
        path.prepend(node)
        node = prev[node]
    return path

This traces backward from the target to the source, giving us the complete shortest path in O(V) time.

Comparison with Bellman-Ford

PropertyDijkstraBellman-Ford
Negative weights Not supported Supported (detects negative cycles)
Time complexity O((V+E) log V) O(V × E)
Strategy Greedy (visit closest node) Relax all edges V-1 times
Implementation Needs priority queue Simple nested loops
Best for Non-negative weights, sparse graphs Graphs with negative weights

Bellman-Ford is simpler to implement but much slower. Use Dijkstra when you can guarantee non-negative weights (which is the case for most real-world applications like road networks, where distances and times are always positive).

Complexity Analysis

Complexity

With binary heap: O((V + E) log V) — each of the V extract-min operations costs O(log V), and each of the E relaxations may trigger an insert costing O(log V).
With unsorted array: O(V² + E) — scanning for the minimum takes O(V) and is done V times.
Space: O(V + E) for the graph, distances, predecessors, and priority queue.

Where Dijkstra's Algorithm Is Used

Application How it uses shortest paths
GPS navigation Find the fastest route between two locations on a road network
Network routing (OSPF) Each router computes shortest paths to all other routers to build its forwarding table
Game AI pathfinding NPCs navigate terrain with varying movement costs (roads vs. swamps vs. mountains)
Social networks Find degrees of separation or shortest connection between users
Robotics Plan movement paths through environments with obstacles and terrain costs
Telephone networks Route calls through the lowest-cost path across switching centers

Key Takeaways

  • Dijkstra's algorithm finds the shortest path from a source to all other nodes in a weighted graph with non-negative edge weights
  • It works by greedily expanding the closest unvisited node — once a node is visited, its shortest distance is finalized
  • A priority queue (binary heap) makes it efficient: O((V + E) log V)
  • Negative edge weights break the greedy invariant — use Bellman-Ford for those cases
  • A predecessor array lets you reconstruct the actual shortest path, not just its length
  • It's the backbone of GPS navigation, network routing protocols like OSPF, and game AI pathfinding

Try It Yourself — Dijkstra's Shortest Path

Click on the grid to place walls. Click Set Start or Set End, then click a cell to place it. Hit Run to watch Dijkstra explore the grid. Visited cells are shaded, the frontier is highlighted, and the shortest path is drawn at the end.

0
Nodes visited
—
Path length
0
Steps

Dijkstra's algorithm is a masterclass in greedy thinking: by always choosing the closest unvisited node, it systematically builds up shortest paths without ever needing to backtrack. This idea — that local optimal choices lead to a global optimum — is what makes it both beautiful and practical. Next up, we'll see how A* takes this foundation and supercharges it with heuristics.