AlgoViz

Dijkstra's algorithm

medium 22 min

Dijkstra's algorithm finds the shortest distance from one source to every node of a graph whose edge weights are non-negative.

Video lesson · Chapter 1 of 7

The express road loses

0:00 / 5:56

Dijkstra's algorithm in 75 seconds

1:27Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Start at the source. dist(source) = 0, every other node is infinity, and the heap holds (0, source)

Understand it

Start here

Shortest paths when edges have weights

In an unweighted graph, BFS finds shortest paths because every edge costs the same. Give the edges weights (minutes, kilometres, milliseconds) and the fewest hops is no longer the cheapest route. Dijkstra's algorithm (Edsger Dijkstra, 1956) answers: what is the cheapest route from one source ss to every node, when no weight is negative?

What you already know

  • Graphs

    Nodes, weighted edges, adjacency lists {u: [(v, w), ...]}. Recap in intro to graphs.

  • Min-heaps

    heapq pops the smallest tuple in O(log⁡n)O(\log n). Recap in priority queues and heap operations.

  • BFS

    A FIFO queue explores in order of hop count. Dijkstra swaps the queue for a min-heap and explores in order of distance.

The core move

Relaxation

Every node vv carries a tentative distance dist[v]\text{dist}[v]: the best route found so far, an upper bound on the true distance δ(s,v)\delta(s, v). To relax the edge u→vu \to v with weight ww is to ask: is going through uu better than what vv has now? If so, take it and remember uu as vv's predecessor.

Relaxing edge (u, v) with weight w

if dist[u]+w(u,v)<dist[v]:dist[v]←dist[u]+w(u,v),prev[v]←u\text{if } \text{dist}[u] + w(u, v) < \text{dist}[v]: \quad \text{dist}[v] \leftarrow \text{dist}[u] + w(u, v), \quad \text{prev}[v] \leftarrow u
Relaxation only ever lowers a distance, and dist[v]≥δ(s,v)\text{dist}[v] \ge \delta(s, v) always holds, because every value it writes is the length of a real path.

One relaxation

Strictly less: an equal distance changes nothing and should not push a new entry.
Relaxation in the simple graphCheckResult
A to B (w 4)0+4<∞0 + 4 < \inftydist(B) = 4
C to B (w 1)2+1<42 + 1 < 4dist(B) = 3, prev(B) = C
C to D (w 8) then B to D (w 5)1010, then 3+5<103 + 5 < 10dist(D) = 8
D to E (w 2)8+2<128 + 2 < 12dist(E) = 10
The same node can improve several times. Only the last value survives.

The algorithm

A min-heap loop with lazy deletion

The Dijkstra loop

The only difference from BFS: the container is a min-heap keyed by distance, and a node is final when it is popped, not when it is first seen.
Python
import heapqdef dijkstra(graph, src):    dist = {v: float("inf") for v in graph}    prev = {v: None for v in graph}    dist[src] = 0    pq = [(0, src)]                          # (distance, node): distance first!    while pq:        d, u = heapq.heappop(pq)             # closest entry        if d > dist[u]:            continue                         # stale: u was settled cheaper        for v, w in graph[u]:            nd = d + w            if nd < dist[v]:                 # relax                dist[v] = nd                prev[v] = u                heapq.heappush(pq, (nd, v))    return dist, prevgraph = {    "A": [("B", 4), ("C", 2)],    "B": [("A", 4), ("C", 1), ("D", 5)],    "C": [("A", 2), ("B", 1), ("D", 8), ("E", 10)],    "D": [("B", 5), ("C", 8), ("E", 2), ("F", 6)],    "E": [("C", 10), ("D", 2), ("F", 3)],    "F": [("D", 6), ("E", 3)],}dist, prev = dijkstra(graph, "A")print(dist)   # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}
The standard Python version. Run it: the output matches the walkthrough below.
Edit and run it in your browser

Six implementation details

  • Min-heap

    Extract the closest entry in O(log⁡V)O(\log V). Tuples are (distance, node) so the heap orders by distance.

  • Lazy deletion

    Never search the heap. Push a fresh entry on every improvement and skip stale ones on pop.

  • Distance map

    dist[v]: the best known distance, starting at ∞\infty.

  • Predecessor map

    prev[v]: who gave vv its distance. Rebuilds every route afterwards.

  • Non-negative weights

    Required for the greedy choice to be correct. One negative edge breaks it.

  • Adjacency list

    Iterate a node's neighbours in O(deg)O(\text{deg}), so all relaxations total O(E)O(E).

Worked example

Tracing the simple graph from A

Six nodes A to F, nine two-way edges: A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2, D–F 6, E–F 3. Source A. Step through it in the visualizer too.

  1. 1

    Initialise

    dist: A 00, everything else ∞\infty. Heap: (0, A).

  2. 2

    Settle A

    Relax A–B and A–C: B =4= 4, C =2= 2. Heap: (2, C), (4, B).

  3. 3

    The greedy choice: C, not B

    C at 2 is the minimum, so it is settled. Through C, B improves 4→34 \to 3; D =10= 10, E =12= 12. The old (4, B) is now stale.

  4. 4

    Settle B at 3

    B–D: 3+5=8<103 + 5 = 8 < 10. Then (4, B) pops and is skipped.

  5. 5

    Settle D at 8

    D–E: 10<1210 < 12, D–F: 1414. Then (10, D) is stale and skipped.

  6. 6

    Settle E at 10, F at 13

    E–F: 13<1413 < 14. Stale (12, E) and (14, F) are skipped. Final: A 0, B 3, C 2, D 8, E 10, F 13.

dist after each settle

SettledABCDEF
(start)0∞∞∞∞∞
A042∞∞∞
C0321012∞
B032812∞
D03281014
E03281013
F03281013
Bold values are final. Settle order A, C, B, D, E, F follows the distances 0, 2, 3, 8, 10, 13: never decreasing.

Lazy deletion

Stale entries and why they are harmless

When B improved from 4 to 3, the textbook move is decrease-key: find (4, B) inside the heap and lower it. Python's heapq cannot find an entry without an O(n)O(n) scan, so we push (3, B) and leave (4, B) behind. When it finally pops, 4>dist[B]=34 > \text{dist}[B] = 3 tells us it is out of date: skip it. This is the same lazy deletion trick from priority queues.

The life of one node

A node can sit in the heap several times, but only its smallest entry settles it.

Lazy deletion (heapq)

  • Push on every improvement, skip d > dist[u] on pop
  • No index map, about 10 lines of code
  • Heap can grow to O(E)O(E) entries
  • Same O((V+E)log⁡V)O((V + E) \log V) bound

Decrease-key (indexed heap)

  • Needs a node-to-slot map updated on every swap
  • Heap never exceeds VV entries
  • More code, more bugs in an interview
  • Java and C++ standard queues lack it too

Correctness

Why the popped node is final

Claim. When a node uu is popped with d=dist[u]d = \text{dist}[u] (not stale), dist[u]=δ(s,u)\text{dist}[u] = \delta(s, u). Proof by contradiction. Let uu be the first node settled with dist[u]>δ(s,u)\text{dist}[u] > \delta(s, u). Take a true shortest path from ss to uu, and let yy be the first node on it that is not yet settled, with xx just before it (settled, so correct by the choice of uu). When xx was settled, edge x→yx \to y was relaxed, so dist[y]≤δ(s,x)+w(x,y)=δ(s,y)\text{dist}[y] \le \delta(s, x) + w(x, y) = \delta(s, y).

The chain that cannot hold

dist[y]  ≤  δ(s,y)  ≤w≥0  δ(s,u)  <  dist[u]\text{dist}[y] \;\le\; \delta(s, y) \;\underset{w \ge 0}{\le}\; \delta(s, u) \;<\; \text{dist}[u]
yy lies on the path to uu and every remaining edge weight is ≥0\ge 0, so δ(s,y)≤δ(s,u)\delta(s, y) \le \delta(s, u). Then yy has a smaller key than uu and the heap would pop yy first. Contradiction, so every popped node is correct. (If y=uy = u, the first inequality alone already contradicts.)

The proof picture

The greedy choice is safe because leaving the settled region and coming back can only add cost.

Complexity

O((V + E) log V) and when an array wins

Counting heap operations

T(V,E)=O(V+E)⏟pushes ≤ E+1⋅O(log⁡E)+O(V+E)⏟pops⋅O(log⁡E)=O((V+E)log⁡V)T(V, E) = \underbrace{O(V + E)}_{\text{pushes} \,\le\, E + 1} \cdot O(\log E) + \underbrace{O(V + E)}_{\text{pops}} \cdot O(\log E) = O\big((V + E) \log V\big)
Each settled node relaxes its edges once, so there are at most E+1E + 1 pushes (each two-way edge counts as two directed edges) and as many pops. Since E≤V2E \le V^2, log⁡E≤2log⁡V\log E \le 2 \log V, so log⁡E\log E and log⁡V\log V are the same order.

Three ways to find the minimum

Priority structureExtract-minImprove a distanceTotalBest for
Plain array, scan for minO(V)O(V)O(1)O(1)O(V2)O(V^2)Dense graphs, E≈V2E \approx V^2
Binary heap (heapq)O(log⁡V)O(\log V)O(log⁡V)O(\log V) pushO((V+E)log⁡V)O((V + E) \log V)Sparse graphs: roads, networks, grids
Fibonacci heapO(log⁡V)O(\log V) amortisedO(1)O(1) amortised decrease-keyO(E+Vlog⁡V)O(E + V \log V)Theory; constants too large in practice
Space: O(V+E)O(V + E) for the graph, dist and prev, plus up to O(E)O(E) heap entries with lazy deletion (O(V)O(V) with decrease-key).

Where the array version wins

E=Θ(V2)  ⇒  (V+E)log⁡V=Θ(V2log⁡V)  >  Θ(V2)E=Θ(V)  ⇒  Θ(Vlog⁡V)≪Θ(V2)E = \Theta(V^2) \;\Rightarrow\; (V + E) \log V = \Theta(V^2 \log V) \;>\; \Theta(V^2) \qquad E = \Theta(V) \;\Rightarrow\; \Theta(V \log V) \ll \Theta(V^2)
A road network with V=106V = 10^6 and E≈3×106E \approx 3 \times 10^6: about 8×1078 \times 10^7 heap steps against 101210^{12} array scans. A complete graph of 1,000 nodes flips the verdict.

Limits

Why negative edges break it

The proof used w≥0w \ge 0 in one place: "continuing past yy can only add cost". With a negative edge, a route that looks expensive now can become cheaper later, after a node was already declared final. Example (directed): A→B 2, A→C 3, C→B −2-2, B→D 1. The true distances are B =1= 1, D =2= 2.

A negative edge arrives too late

Dijkstra settles B at 2 and D at 3. When C finally relaxes C→B to 1, B is already final, and D was built on the wrong value.
AlgorithmNegative edgesNegative cyclesTime
DijkstraNoNoO((V+E)log⁡V)O((V + E) \log V)
Bellman-FordYesDetects themO(V⋅E)O(V \cdot E): relax all edges V−1V - 1 times
Floyd-Warshall (all pairs)YesDetects themO(V3)O(V^3)
Johnson (all pairs, sparse)Yes, by reweightingDetects themO(VElog⁡V)O(V E \log V)
Adding a constant to every weight to make them positive does not work: it penalises paths with more edges and changes which path is shortest.

Paths

Rebuilding the route with prev

Distances say how far, not which way. Every successful relaxation sets prev[v]=u\text{prev}[v] = u, and the last one written is the final predecessor. Walk from the target back to the source, then reverse.

Walking prev from F

Reversed: A → C → B → D → E → F, and 2+1+5+2+3=132 + 1 + 5 + 2 + 3 = 13.
Python
def path_to(prev, dist, target):    if dist[target] == float("inf"):        return []                         # never reached    path, node = [], target    while node is not None:        path.append(node)        node = prev[node]    return path[::-1]dist = {"A": 0, "B": 3, "C": 2, "D": 8, "E": 10, "F": 13, "Z": float("inf")}prev = {"A": None, "B": "C", "C": "A", "D": "B", "E": "D", "F": "E", "Z": None}print(path_to(prev, dist, "F"))   # ['A', 'C', 'B', 'D', 'E', 'F']print(path_to(prev, dist, "Z"))   # []
Path reconstruction plus an unreachable check. Run it.
Edit and run it in your browser

Variants

Early exit, grids and networks

  • Single target: stop early

    Return when the target is popped (not pushed). Saves work when the target is near; in the London to Rome scene all 10 cities settle anyway.

  • Weighted grids

    Each cell is a node with up to 4 neighbours. Cost can be the cell value, or a max along the path as in minimum effort.

  • Networks

    Signal delay from one router to all: run once, answer is the largest finite dist, or −1-1 if any node is unreachable.

  • Other path costs

    Maximum probability (multiply, use a max-heap) and minimum effort (max of steps) work because the cost never improves by extending a path.

Python
import heapqdef cheapest_walk(grid):    rows, cols = len(grid), len(grid[0])    dist = [[float("inf")] * cols for _ in range(rows)]    dist[0][0] = grid[0][0]    pq = [(grid[0][0], 0, 0)]    while pq:        d, r, c = heapq.heappop(pq)        if d > dist[r][c]:            continue        if (r, c) == (rows - 1, cols - 1):            return d                                   # popped: final        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):            nr, nc = r + dr, c + dc            if 0 <= nr < rows and 0 <= nc < cols and d + grid[nr][nc] < dist[nr][nc]:                dist[nr][nc] = d + grid[nr][nc]                heapq.heappush(pq, (dist[nr][nc], nr, nc))    return -1grid = [[1, 3, 1, 8],        [1, 5, 1, 9],        [4, 2, 1, 1]]print(cheapest_walk(grid))   # 1 + 3 + 1 + 1 + 1 + 1 = 8
Dijkstra on a grid: the cheapest walk from top-left to bottom-right, paying each cell's cost as you enter it.
Edit and run it in your browser

Classic problems that are Dijkstra underneath

Problem (LeetCode)NodeEdge costTwist
743 Network Delay Timerouterdelayanswer is max(dist), −1-1 if unreachable
1631 Path With Minimum Effortcellheight differencepath cost is the max step, not the sum
1514 Path with Maximum Probabilitynodesuccess probabilitymultiply and use a max-heap
778 Swim in Rising Watercellcell heightpath cost is the max cell
787 Cheapest Flights Within K Stops(city, stops)pricestate needs the stop count, or use Bellman-Ford with K + 1 rounds
882 Reachable Nodes in Subdivided Graphnodesubdivisions + 1count leftover moves on each edge
The practice problems at the end of this topic cover the first three in our own words.

Choosing

Dijkstra, BFS, Bellman-Ford or something else

Which shortest-path algorithm?

Dijkstra is the default for one source and non-negative weights. The other branches are special cases that are faster or more general.
DijkstraBFSBellman-Ford
Edge weightsNon-negativeUnweighted (all equal)Any, including negative
TimeO((V+E)log⁡V)O((V + E) \log V)O(V+E)O(V + E)O(V⋅E)O(V \cdot E)
Data structurePriority queue (min-heap)QueueEdge list, V−1V - 1 passes
Best forRoad networks, routingSocial networks, mazesNegative weights, cycle detection

Use Dijkstra when

  • You need shortest paths from one source
  • All edge weights are non-negative
  • The graph is sparse (EE well below V2V^2)
  • You want paths to every node, or one target with early exit

Do not use it when

  • Any weight is negative: use Bellman-Ford
  • The graph is unweighted: BFS is simpler and faster
  • You need all-pairs distances: use Floyd-Warshall
  • A path constraint (at most K stops) changes the state

Recap

Key takeaways

Key points

  • Dijkstra finds single-source shortest paths when every edge weight is ≥0\ge 0; it is BFS with a min-heap keyed by distance.
  • Relax edge (u,v)(u, v): if dist[u]+w<dist[v]\text{dist}[u] + w < \text{dist}[v], lower dist[v]\text{dist}[v], set prev[v]=u\text{prev}[v] = u and push.
  • A node is final when popped, not when first pushed; stale entries (d>dist[u]d > \text{dist}[u]) are skipped. That is lazy deletion.
  • Correctness: any route that leaves the settled set is already at least as long, and non-negative edges only add.
  • Time O((V+E)log⁡V)O((V + E) \log V) with a binary heap, O(V2)O(V^2) with an array (better when dense), O(E+Vlog⁡V)O(E + V \log V) with a Fibonacci heap.
  • Negative edges break it: use Bellman-Ford. Rebuild routes by walking prev back from the target and reversing.

Sources