Discrete Mathematics and Combinatorics

How Dijkstra's Algorithm Finds Shortest Paths

Trace Dijkstra's method step by step on a small network, see why it is correct, and learn when it fails.

Key takeaways

  • Each vertex carries a tentative distance that can only go down until the vertex is declared final.
  • The vertex with the smallest tentative distance among the unfinished ones is always safe to finalize.
  • Recording which neighbor produced each improvement lets you reconstruct the routes at the end.
  • The method requires nonnegative edge weights, and a single negative edge can make it give wrong answers.
  • With a priority queue it is fast enough to be a basic tool in routing software and many other systems.

Dijkstra's algorithm finds the shortest route from one starting point to every other point in a network whose link lengths are never negative. It keeps a best-known distance for each point and repeatedly locks in the closest point not yet finished, then uses it to improve the estimates of its neighbors.

The network is a weighted graph: vertices (points) joined by edges (links), each edge carrying a number such as kilometers, minutes or cost. The length of a path is the sum of the numbers along it. Edsger Dijkstra devised the method in 1956 and published it in 1959.

The steps

  1. Give the start vertex distance 0 and every other vertex distance ∞ (infinity, meaning no route found yet).
  2. Among the unfinished vertices, choose the one with the smallest tentative distance. Call it u.
  3. Mark u as finished.
  4. For each unfinished neighbor v, compute (distance of u) + (length of edge u–v). If this beats v's tentative distance, replace it and note that v was reached from u.
  5. Repeat from step 2 until every reachable vertex is finished, or until your target is.

The update in step 4 is called relaxing the edge. Everything else is bookkeeping.

The main loop of Dijkstra's algorithm
Record Remember which vertex gave the improvement Relax Try to improve each unfinished neighbor Choose Pick the unfinished vertex with the smallest distance Finish Declare that distance final 1 2 3 4 Choose Pick the unfinished vertex with the smallest distance 1 Finish Declare that distance final 2 Relax Try to improve each unfinished neighbor 3 Record Remember which vertex gave the improvement 4

A worked example

A network has six places, S, A, B, C, D and T, with two-way roads of these lengths:

Road Length Road Length
S–A 7 B–D 6
S–B 2 C–D 2
B–A 3 C–T 5
A–C 4 D–T 9
B–C 8

Find the shortest route from S to T. Each row below shows the tentative distances after finishing the named vertex. A dash marks a vertex already finished earlier.

Finish A B C D T
S (0) 7 2 ∞ ∞ ∞
B (2) 5 — 10 8 ∞
A (5) — — 9 8 ∞
D (8) — — 9 — 17
C (9) — — — — 14
T (14) — — — — —

Notice three improvements. The direct road to A had length 7, but going through B gives 2 + 3 = 5. Then C drops from 10 to 9 by way of A. Finally T drops from 17 to 14 once C is finished.

To recover the route, follow the records backward. T was last improved from C, C from A, A from B and B from S. The shortest route is S, B, A, C, T, with length 2 + 3 + 4 + 5 = 14.

It uses four roads, even though routes with three exist. Fewest roads and shortest distance are different goals.

Why the greedy choice is safe

The key claim is that when a vertex u is chosen in step 2, its tentative distance is already the true shortest distance.

Suppose all previously finished vertices have correct distances. Take any route from the start to u. Somewhere it first steps from the finished set to an unfinished vertex w. Because the edge into w was relaxed when its predecessor was finished, the tentative distance of w is at most the length of the route up to w. And u was chosen as the smallest, so the distance of u is at most that of w. The rest of the route, from w to u, has nonnegative length. So the whole route is at least as long as the tentative distance of u.

That is induction on the number of finished vertices. The step "the rest of the route has nonnegative length" is exactly where negative weights would break the argument.

What goes wrong with negative edges

Take three vertices with one-way edges: S to A of weight 2, S to B of weight 5 and B to A of weight −4. The algorithm finishes A first, at distance 2, because 2 is smaller than 5. But the route S, B, A has length 5 − 4 = 1. By then A has been locked.

A tempting repair is to add 4 to every edge so that none is negative. It fails. The direct route to A becomes 6, while the route through B becomes 9 + 0 = 9. Adding a constant penalizes routes with more edges, so it can change which route is shortest.

For negative weights, use the Bellman–Ford method, which relaxes every edge repeatedly. It is slower, but it handles negative edges and detects cycles whose total length is negative. When such a cycle can be reached, "shortest" has no meaning, since going around it again always helps.

The shortest path tree

Keep the record of who improved whom, and by the end you have more than one route. Each vertex except the start points back to a single predecessor. Together those links form a tree rooted at the start, and the path inside the tree from the start to any vertex is a shortest one.

In the worked example, the predecessors are as follows. B comes from S. A comes from B. D also comes from B. C comes from A, and T comes from C. Five links connect six places. The road from S to A, the road from C to D and the others left out of the tree are never needed for journeys starting at S.

Ties can occur. If two neighbors offer the same distance, either predecessor is correct, and different programs may report different routes of equal length.

A useful check on any finished answer is that no edge can still be relaxed. For every road joining u and v, the distance of v must be at most the distance of u plus the road length, and the same in the other direction. Test the road D to T: 8 + 9 = 17 is not less than 14, so it offers nothing. Test C to D: 9 + 2 = 11 is not less than 8.

Why not try every route?

You could list all routes from S to T and compare them. On six places that is manageable. On a grid of streets it is not. Going from one corner of a 10 by 10 block grid to the opposite corner, moving only right or up, already allows 184,756 different routes, the number of ways to choose which 10 of the 20 moves go right.

Dijkstra's method avoids the explosion because it never needs to remember all the ways of reaching a vertex. Only the best one matters, since any shortest route through that vertex can use the best way of getting there. This property, that optimal solutions are built from optimal pieces, is the heart of the technique called dynamic programming.

Speed and data structures

Let V be the number of vertices and E the number of edges. The main cost is finding the smallest tentative distance again and again.

Method of finding the minimum Running time grows like Best suited to
Scan a plain list V² Dense networks
Binary heap (V + E) log V Sparse networks such as roads
Fibonacci heap E + V log V Mainly of theoretical interest

A heap is a data structure that keeps items arranged so the smallest is quick to extract. The growth notation is explained in Big O notation.

Relatives of the method

If every edge has the same length, you do not need a priority queue. Breadth-first search, which visits all vertices one step away, then two steps away and so on, gives shortest paths directly.

When you have a particular destination, the A\* search method adds an estimate of the remaining distance, such as the straight-line distance on a map. Vertices that lead toward the goal are examined first. If the estimate never overstates the true remaining distance, and is consistent from one vertex to its neighbors, the answer stays optimal while much less of the network is explored.

Large route planners go further and precompute shortcuts, so that a query across a continent touches only a small part of the road network.

Dijkstra's algorithm also resembles Prim's algorithm for spanning trees. Both grow a tree one vertex at a time. Prim ranks a vertex by the weight of the single edge that would attach it, while Dijkstra ranks it by total distance from the start. The resulting trees can differ.

Modeling tricks

Many problems become shortest path problems once you choose the vertices cleverly.

  • Turn costs. Make each vertex a road segment instead of a junction, so that a left turn can carry its own delay.
  • Limited resources. Let a vertex be a pair (location, fuel remaining). Edges change both parts.
  • Most reliable route. If each link works independently with some probability, you want the largest product. Replacing each probability p with −log p, which is nonnegative when 0 < p ≤ 1, turns the product into a sum to be minimized.

Say two routes have link probabilities 0.9 and 0.9, or a single link of 0.8. The products are 0.81 and 0.80, so the two-link route is slightly more reliable.

Common mistakes

  • Finishing a vertex as soon as you first reach it. It must wait until it has the smallest tentative distance.
  • Stopping when the target first receives a number. In the example, T showed 17 before the true value of 14 appeared.
  • Updating finished vertices, which is unnecessary when weights are nonnegative.
  • Forgetting to record predecessors, which leaves you with a length but no route.
  • Using it to visit many places in the best order. That is the traveling salesperson problem, a much harder question.

Written for 4Mathematics with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 45 articles in Discrete Mathematics and Combinatorics →

Latest news on this topic