Dijkstra's algorithm finds the shortest path from one source to every other vertex when all edge weights are non-negative. It is greedy: it repeatedly settles the unsettled vertex with the smallest tentative distance, then relaxes that vertex's outgoing edges. With a binary-heap priority queue it runs in O((V + E) log V). Link-state routing protocols such as OSPF and IS-IS run it on every router, and map and navigation engines are built on its ideas.
Think of it like
A network of burning fuses
Lay a fuse along every road, with length proportional to the road's length, and light the fuse at the source. Fire spreads along all fuses at the same speed, and the moment the flame first reaches a junction is exactly that junction's shortest distance. Dijkstra simulates this fire in order of arrival time. It never needs to revisit a junction, because a flame that arrives later can only be slower. Negative weights would be fuses that burn backwards in time, which breaks the simulation.
The idea: relaxation
Every shortest-path algorithm keeps a tentative distance dist[v], an upper bound on the true distance, starting at infinity (0 for the source). Relaxing an edge u → v asks: is going through u a better way to reach v? If so, lower dist[v] and remember u as v's parent.
Algorithms differ only in which edges they relax and in what order. Bellman-Ford & Floyd-Warshall relaxes every edge V - 1 times. Dijkstra is smarter: it relaxes each edge exactly once, at the moment its tail vertex is settled with its final distance.
How it works
- 1
Initialize
dist[s] = 0, every otherdistis infinity. Push(0, s)into a min-priority queue. - 2
Extract the closest vertex
Pop the pair
(d, u)with the smallestd. - 3
Skip stale entries
If
d > dist[u], this entry was superseded by a better one pushed later. Ignore it. - 4
Settle and relax
dist[u]is now final. For every edgeu → vwith weightw, ifd + w < dist[v], updatedist[v], setparent[v] = uand push(dist[v], v). - 5
Repeat until the queue is empty
Or stop as soon as the target is popped, if you only need one destination.
Worked example
Undirected graph with edges A-B 4, A-C 2, B-C 1, B-D 5, C-D 8, C-E 10, D-E 2, source A. Notice how B is first given distance 4, then improved to 3 through C, leaving a stale (4, B) entry in the heap. The visualization above replays this kind of run step by step.
| Step | Pop | Action | dist (A, B, C, D, E) |
|---|---|---|---|
| Init | none | push (0, A) | 0, ∞, ∞, ∞, ∞ |
| 1 | (0, A) | settle A; B → 4, C → 2 | 0, 4, 2, ∞, ∞ |
| 2 | (2, C) | settle C; B: 2 + 1 = 3 < 4; D → 10; E → 12 | 0, 3, 2, 10, 12 |
| 3 | (3, B) | settle B; D: 3 + 5 = 8 < 10 | 0, 3, 2, 8, 12 |
| 4 | (4, B) | stale (4 > 3): skip | unchanged |
| 5 | (8, D) | settle D; E: 8 + 2 = 10 < 12 | 0, 3, 2, 8, 10 |
| 6 | (10, D) | stale (10 > 8): skip | unchanged |
| 7 | (10, E) | settle E; nothing improves | 0, 3, 2, 8, 10 |
| 8 | (12, E) | stale: skip; heap empty | final |
Why the greedy choice is correct
Claim: when u is popped with the smallest tentative distance among unsettled vertices, dist[u] is the true shortest distance. Suppose not, and some path P from s to u is shorter. P starts inside the settled set, so it must leave it somewhere: let x → y be the first edge of P from a settled x to an unsettled y. Because x is settled (correctly, by induction) and its edges were relaxed, dist[y] is at most the length of P up to y.
The step len(P up to y) ≤ len(P) says that extending a path can never make it shorter. That is exactly where non-negative weights are required, and exactly what fails when they are not.
Why negative edges break it
Take directed edges A→B 1, A→C 2, C→B -2, B→D 1 with source A. Dijkstra settles B at distance 1 (the smallest), relaxes B→D to give D = 2, then settles C at 2 and discovers C→B would make B = 0. But B is already settled and D was computed from the old value. The true answers are B = 0 and D = 1.
What goes wrong
- Settled distances are no longer final
- Settle-once implementations return wrong answers
- Re-pushing improved vertices fixes correctness (without negative cycles) but can take exponential time
- With a negative cycle, there is no shortest path at all
What to use instead
- Bellman-Ford & Floyd-Warshall:
O(V · E), detects negative cycles - DAG relaxation in Topological Sort order:
O(V + E)with any weights - Johnson's algorithm: reweight with potentials, then run Dijkstra
- Never "add a constant to every edge" (see the warning below)
Path reconstruction
Set parent[v] = u on every successful relaxation. The final parent pointers form a shortest-path tree rooted at the source. To print the route to t, follow parents from t back to s and reverse, exactly as in Breadth-First Search. If dist[t] is still infinity, t is unreachable.
Implementations and their complexity
Dijkstra performs V extract-min operations and up to E decrease-key (or push) operations. The priority queue decides the total cost.
| Priority queue | Extract-min | Decrease / push | Total | Best for |
|---|---|---|---|---|
| Unsorted array | O(V) | O(1) | O(V²) | Dense graphs, E close to V² |
| Binary heap (lazy deletion) | O(log V) | O(log V) | O((V + E) log V) | Sparse graphs: the default |
| Fibonacci heap | O(log V) amortized | O(1) amortized | O(E + V log V) | Theory; large constants in practice |
| Dial's buckets (integer weights ≤ C) | O(C) amortized | O(1) | O(E + V · C) | Small integer weights |
Variants
Multi-source Dijkstra
To find each vertex's distance to the nearest of several sources (closest hospital, nearest warehouse), push every source with distance 0 before starting. As with multi-source BFS, this equals one run from a virtual super-source and costs the same as a single Dijkstra.
Shortest path with at most k stops
With a hop limit, a cheaper path that uses more edges can block a pricier path that fits the limit, so pruning by dist[v] alone is wrong. Expand the state to (vertex, edges used), or keep, for each vertex, the fewest edges with which it has been popped and skip pops that are no better on either criterion. Bellman-Ford with k + 1 rounds is the other standard solution.
import heapq
def find_cheapest_price(n, flights, src, dst, k):
adj = [[] for _ in range(n)]
for u, v, w in flights:
adj[u].append((v, w))
fewest = [float("inf")] * n # fewest edges used when u was popped
heap = [(0, src, 0)] # (cost, vertex, edges used)
while heap:
cost, u, edges = heapq.heappop(heap)
if u == dst:
return cost # popped in cost order: cheapest valid route
if edges >= fewest[u] or edges > k:
continue # dominated: costs more AND uses no fewer edges
fewest[u] = edges
for v, w in adj[u]:
heapq.heappush(heap, (cost + w, v, edges + 1))
return -1Bidirectional Dijkstra
For a single source-target query, run one search forward from s and one backward from t (on reversed edges), alternating. Track the best complete path μ seen whenever an edge connects the two searched regions. Stop when the two heap minimums sum to at least μ. Each search explores roughly a ball of half the radius, which on road networks can mean several times fewer settled vertices.
Other objectives
- Minimax (bottleneck) paths: replace
dist[u] + wwithmax(dist[u], w)to minimize the largest step (Path With Minimum Effort, Swim in Rising Water). - Most reliable path: maximize the product of probabilities with a max-heap. It works because multiplying by a probability ≤ 1 never increases the value, the analogue of non-negative weights.
- Counting shortest paths: when
d + w == dist[v], addways[u]toways[v]; when it is strictly smaller, resetways[v] = ways[u]. - Goal-directed search: add a heuristic estimate of the remaining distance and you get A* Pathfinding.
Complexity
| Implementation | Time | Space | Notes |
|---|---|---|---|
| Array scan (no heap) | O(V²) | O(V) | Best for dense graphs |
| Binary heap, lazy deletion | O((V + E) log V) | O(V + E) | Default choice; heap may hold E entries |
| Indexed binary heap, decrease-key | O((V + E) log V) | O(V) | Heap never exceeds V entries |
| Fibonacci heap | O(E + V log V) | O(V) | Amortized; rarely faster in practice |
| Dial's buckets (weights ≤ C) | O(E + V · C) | O(V + C) | Circular array of C + 1 buckets |
All bounds assume adjacency lists (except the array version, which also works with a matrix) and non-negative edge weights.
Implementation
`adj[u]` holds `(v, w)` pairs with `w ≥ 0`. The example is the worked example above, with A to E numbered 0 to 4.
import heapq
def dijkstra(adj: list[list[tuple[int, int]]], source: int) -> tuple[list[float], list[int]]:
n = len(adj)
dist = [float("inf")] * n
parent = [-1] * n
dist[source] = 0
heap = [(0, source)] # (distance, vertex)
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]: # stale entry: u already settled with less
continue
for v, w in adj[u]:
nd = d + w
if nd < dist[v]: # relax u -> v
dist[v] = nd
parent[v] = u
heapq.heappush(heap, (nd, v)) # lazy: push a fresher entry
return dist, parent
def shortest_path(parent: list[int], dist: list[float], target: int) -> list[int]:
if dist[target] == float("inf"):
return [] # unreachable
path = []
v = target
while v != -1:
path.append(v)
v = parent[v]
return path[::-1]
edges = [(0, 1, 4), (0, 2, 2), (1, 2, 1), (1, 3, 5), (2, 3, 8), (2, 4, 10), (3, 4, 2)]
adj = [[] for _ in range(5)]
for u, v, w in edges: # undirected: add both directions
adj[u].append((v, w))
adj[v].append((u, w))
dist, parent = dijkstra(adj, 0)
print(dist) # [0, 3, 2, 8, 10]
print(shortest_path(parent, dist, 4)) # [0, 2, 1, 3, 4]Key takeaways
- Dijkstra settles vertices in increasing order of distance and relaxes each edge once; it requires non-negative weights.
- The greedy step is correct because extending a path with non-negative edges can never make it shorter.
- Use a binary heap with lazy deletion (
if d > dist[u]: continue) forO((V + E) log V); use theO(V²)array version on dense graphs. - Record
parent[v]on every successful relaxation to reconstruct paths; the parents form a shortest-path tree. - Variants include multi-source, hop-limited (expanded state), bidirectional, minimax and max-probability searches.
Common pitfalls
- Forgetting the stale-entry check, which reprocesses vertices and can degrade performance badly.
- Running Dijkstra on graphs with negative edges, or "fixing" them by adding a constant to every weight.
- Marking vertices visited when they are pushed (as in BFS) instead of when they are popped, which freezes non-final distances.
- Integer overflow when adding weights to an
INT_MAXsentinel; use 64-bit distances and check for infinity. - Pruning by distance alone in hop-limited problems such as Cheapest Flights Within K Stops.
Interview tips
- Write the lazy-deletion version from memory; it is short and avoids needing a decrease-key heap.
- Explain the correctness argument in one sentence: the popped vertex cannot be improved because all other routes are at least as long already and edges are non-negative.
- State the trade-off between
O((V + E) log V)andO(V²)and when each wins. - If you only need one target, return when it is popped (not when it is first pushed).
Real-world applications
- Link-state routing protocols (OSPF, IS-IS) compute routing tables with Dijkstra.
- Navigation and map services, usually combined with A* and preprocessing such as contraction hierarchies.
- Network latency and cost optimization in telecom and data-center fabrics.
- Robot motion planning on weighted grids and roadmaps.
- Game AI pathfinding with terrain costs.
- Flight and transit itinerary search (with time-dependent or multi-criteria extensions).
Practice problems
Test yourself
In the lazy-deletion implementation, what does if d > dist[u]: continue accomplish?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.