Reconstructing the path
After this: Walk back through the parents from the goal to the start.
On this page · 7 sections · 4 checks
In the last lesson, Dijkstra's algorithm told us that E is 7 away from A. But a map app must also show the route. Which way do you go?
The table of distances does not say. So we keep one more note for each node, and the route comes out of those notes.
A note at each node
The idea is small. Whenever we improve a node's distance, we also write down the node that the improvement came from. That node is its . It answers the question "how did I get here?".
Here are the three nodes again: A→B 4, A→C 1, C→B 2.
- Relaxing A→B sets B to 4, so B's parent is A.
- Relaxing A→C sets C to 1, so C's parent is A.
- Relaxing C→B improves B to 3, so B's parent changes to C.
The old parent is replaced, because it belonged to the old distance. A has no parent, because it is the start.
Now we can find the route to B.
- Start at B. Its parent is C.
- Go to C. Its parent is A.
- Go to A. It has no parent, so we stop.
That walk gave B, C, A. It runs backwards, from the goal to the start. If we reverse it, we get the route: A → C → B.
Five nodes
Here is the same thing on the full graph. In this table, B ← C means "B's parent is C". Each row is one edge that improved a distance.
| Edge relaxed | New distance | Parent written |
|---|---|---|
| A→B | B = 4 | B ← A |
| A→C | C = 1 | C ← A |
| C→B | B = 3 | B ← C, replacing A |
| C→D | D = 6 | D ← C |
| B→D | D = 4 | D ← B, replacing C |
| D→E | E = 7 | E ← D |
The last parent written is the one that stays, because it goes with the best distance. The final parents are B ← C, C ← A, D ← B and E ← D. A has none.
To find the path to E, walk backwards: E, D, B, C, A. Then reverse it: A → C → B → D → E, which costs 7.
The code
The lines that write the parents are already in the code from the last lesson. This function reads them.
def path_to(parents, goal): if goal not in parents: # never relaxed: no parent was ever written return None path = [] node = goal while node is not None: # walk the parents back to the start path.append(node) node = parents[node] path.reverse() # the walk went backwards return path static List<String> pathTo(Map<String, String> parents, String goal) { if (!parents.containsKey(goal)) return null; // never relaxed: no parent was ever written LinkedList<String> path = new LinkedList<>(); for (String node = goal; node != null; node = parents.get(node)) { path.addFirst(node); // walking backwards, so add at the front } return path; }Here is how to read it.
- The first line checks that the goal has an entry in
parents. If it has none, there is no path, and the function returns Nonenull. The section below explains why. - The loop starts at the goal and moves to each node's parent. It stops at the start, whose parent is Nonenull.
- The route has to read forwards. The Python version collects the nodes and reverses the list at the end. The Java version adds each node at the front, so the list is already in the right order.
distances, parents = dijkstra(graph, "A")print(" -> ".join(path_to(parents, "E")), "costs", distances["E"])print(" -> ".join(path_to(parents, "D")), "costs", distances["D"])A -> C -> B -> D -> E costs 7 A -> C -> B -> D costs 4
Dijkstra.Result result = Dijkstra.run(graph, "A");System.out.println(String.join(" -> ", Dijkstra.pathTo(result.parents(), "E")) + " costs " + result.distances().get("E"));System.out.println(String.join(" -> ", Dijkstra.pathTo(result.parents(), "D")) + " costs " + result.distances().get("D"));A -> C -> B -> D -> E costs 7 A -> C -> B -> D costs 4
No entry in parents, no path
Sometimes no route exists. If we run from C, no edge leads to A. So A is never relaxed, it never gets a parent, and its distance stays at ∞. When we ask for the path to A, the answer is Nonenull.
distances, parents = dijkstra(graph, "C")print(distances["A"], path_to(parents, "A"))inf None
Dijkstra.Result result = Dijkstra.run(graph, "C");int d = result.distances().get("A");System.out.println((d == Integer.MAX_VALUE ? "inf" : String.valueOf(d)) + " " + Dijkstra.pathTo(result.parents(), "A"));inf null
Watch it happen
Each relax step says which parent it writes. Watch B's parent change at the second pop.
- Dijkstra from AStart from A. At the first pop, B's parent becomes A. At the second pop, it becomes C. D's parent changes from C to B. Each relax step tells you which parent it writes.
- Dijkstra from C
Pick a start node and run an algorithm.
Check yourself
Dijkstra's algorithm from A finishes with these parents: B ← C, C ← A, D ← B, E ← D. What is the path to D?
When does Dijkstra's algorithm write a node's parent?
This runs Dijkstra's algorithm from A on the lesson's graph. What does it print?
distances, parents = dijkstra(graph, "A")print(" -> ".join(path_to(parents, "E")), "costs", distances["E"])print(" -> ".join(path_to(parents, "D")), "costs", distances["D"])Dijkstra.Result result = Dijkstra.run(graph, "A");System.out.println(String.join(" -> ", Dijkstra.pathTo(result.parents(), "E")) + " costs " + result.distances().get("E"));System.out.println(String.join(" -> ", Dijkstra.pathTo(result.parents(), "D")) + " costs " + result.distances().get("D"));Dijkstra's algorithm runs from C. What does path_to(parents, "A")pathTo(parents, "A") return, and why?
Connect
- Write a parent every time an edge is relaxed successfully, so the last parent written is the one that stays.
- Walk the parents back from the goal, then reverse the result: A → C → B → D → E.
- Recognise a node that cannot be reached: it never gets a parent, and its distance stays at ∞.