Kolton Ndoj

Dijkstra's algorithm: the spreading wave of shortest paths

Inside every route planner, and in the way internet routers pick paths for your data

What problem does it solve?

What's the shortest route from here to there through a network of roads with different lengths?

The big idea

Imagine pouring water at the start: it spreads along every road at the same speed, and the first moment it touches a crossroads is the shortest distance to that crossroads. Dijkstra simulates that wave by always settling the closest not-yet-settled place next. Once a place is settled, nothing later can beat it: any other route would have to leave through a place that is already at least as far away, and roads never have negative length.

How it works, step by step

  1. 1. Give the start distance 0 and every other place distance ∞.
  2. 2. Pick the unsettled place with the smallest distance and mark it settled.
  3. 3. For each road leaving it, check whether going through it gives a neighbour a shorter distance, and update if so.
  4. 4. Repeat until the destination is settled.
  5. 5. Follow the 'came from' arrows backward to read off the route.

The key formula

d(v)←min⁡(d(v),  d(u)+w(u,v))d(v) \leftarrow \min\big(d(v),\; d(u) + w(u,v)\big)
d(v)d(v)
the best distance to place v found so far
uu
the place just settled
w(u,v)w(u,v)
the length (or travel time) of the road from u to v

How fast is it?

With a priority queue it takes about (V + E) log V steps for V places and E roads. That's fine for a city but too slow to answer millions of continent-wide queries a second, which is why real map apps preprocess the map (see A*). It also breaks if some roads have negative length.

Try it yourself

Fun fact

Edsger Dijkstra invented it in 1956 in about twenty minutes, sitting at a café terrace in Amsterdam with his fiancée, without pencil and paper. He later said avoiding pencil and paper forced him to keep it simple.

Related

Play with the live demo →

Maps · Intermediate