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).
- Give the start vertex final value 0 and order of labelling 1.
- 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.
- 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.
- Repeat steps 2 and 3 until the destination (or every vertex) has a final value.
- 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 solutionHide solution
- A: final value 0. Working values: B 7, C 5.
- C has the smallest, so C is final at 5 (order 2). From C: B (not smaller than 7, so not written), E .
- B is final at 7 (order 3). From B: D , E (smaller than 15, so write 13).
- E is final at 13 (order 4). From E: D (replaces 17), F .
- D is final at 16 (order 5). From D: F (replaces 25).
- F is final at 24 (order 6).
- Trace back: (D), (E), (B), (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
Quiz me on this topic10 questions, marked as you go.Make a practice paperPick the marks and difficulty. Print it with a mark scheme.
Both are part of Premium.