Skip to main content
Examonaut

Topic 2 · Lesson 2 of 4

Dijkstra's algorithm

Shortest paths

Dijkstra's algorithm finds the shortest route from one vertex to every other vertex. Each vertex gets a box in which you record: the order of labelling, its final value (the shortest distance from the start), and its working values (the temporary values it is given along the way, in order).

  1. Give the start vertex final value 0 and order of labelling 1.
  2. For the vertex just given a final value, look at each vertex joined to it that does not have a final value. Its working value is the final value just found plus the arc weight. Write it in, but only if it is smaller than any working value already there.
  3. Of all the vertices without final values, find the one with the smallest working value. Make that its final value and give it the next order of labelling.
  4. Repeat steps 2 and 3 until the destination (or every vertex) has a final value.
  5. Find the route by tracing back from the destination: an arc XY is on the route if the final value of Y minus the final value of X equals the weight of XY.

On a directed network, only travel along arcs in the direction of the arrows.

Worked example

Dijkstra's algorithm

Find the shortest route from A to F in the network above.

Show solution
  1. A: final value 0. Working values: B 7, C 5.
  2. C has the smallest, so C is final at 5 (order 2). From C: B 5+4=95 + 4 = 9 (not smaller than 7, so not written), E 5+10=155 + 10 = 15.
  3. B is final at 7 (order 3). From B: D 7+10=177 + 10 = 17, E 7+6=137 + 6 = 13 (smaller than 15, so write 13).
  4. E is final at 13 (order 4). From E: D 13+3=1613 + 3 = 16 (replaces 17), F 13+12=2513 + 12 = 25.
  5. D is final at 16 (order 5). From D: F 16+8=2416 + 8 = 24 (replaces 25).
  6. F is final at 24 (order 6).
  7. Trace back: 24−8=1624 - 8 = 16 (D), 16−3=1316 - 3 = 13 (E), 13−6=713 - 6 = 7 (B), 7−7=07 - 7 = 0 (A). The route is A B E D F, length 24.

The working values in this example are B 7; C 5; D 17, 16; E 15, 13; F 25, 24. The replacements (17 by 16, 15 by 13, 25 by 24) are exactly what the method marks look for.

Uses of the final values

  • The final values give the shortest distance from the start to every vertex, so one run answers several questions.
  • For the shortest route that must pass through a vertex V, add the shortest distance from the start to V and from V to the destination. Running Dijkstra's algorithm from the destination gives the second part for every possible V at once.
  • To find the shortest route avoiding a vertex or an arc, delete it and look again; often the final values already tell you the answer.

Practise this topic

Both are part of Premium.