Card 06/ 09
Grid DP Example: The Cheapest Route Through a Toll Grid
The same table with a minimum in place of the sum gives the cheapest route and, read back, the route itself.
A grid table finds the cheapest route as readily as it counts routes: each cell holds its own cost plus the cheaper of the two cells it can be entered from, and walking back from the corner recovers the route. The surface is a road map of tolls, where the reader must see that taking the cheapest next road is not the same as taking the cheapest route.
A driver crosses a city laid out as a 3 by 3 grid of districts, from the top-left to the bottom-right, moving only east or south, and pays each district's toll on entering it, the first included. The tolls, row by row, are 1 1 8, then 4 9 9, then 1 1 1. The state is cheapest[r][c], the least total toll to reach district (r, c), and cheapest[r][c] = toll[r][c] + min(cheapest[r − 1][c], cheapest[r][c − 1]), with a missing neighbour treated as unreachable. A run filled the table row by row.
Filling cheapest[r][c] for the toll grid 1 1 8, 4 9 9, 1 1 1
Row 0
The top row can be reached only from the west, so each district adds its toll to the total before it: 1, then 1 + 1 = 2, then 2 + 8 = 10.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 1 | 2 | 10 |
Row 1
Column 0 comes only from the north: 1 + 4 = 5. Column 1 takes the cheaper of 2 from the north and 5 from the west, 2, plus 9: 11. Column 2 takes the cheaper of 10 and 11, plus 9: 19.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 1 | 2 | 10 |
| 1 | 5 | 11 | 19 |
Row 2
Column 0 is 5 + 1 = 6. Column 1 takes the cheaper of 11 from the north and 6 from the west, plus 1: 7. The corner takes the cheaper of 19 and 7, plus 1: 8.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 1 | 2 | 10 |
| 1 | 5 | 11 | 19 |
| 2 | 6 | 7 | 8 |
The cheapest crossing costs 8. To find the route, start at the corner and step back to whichever neighbour holds the smaller total: from 8 to 7 on the west, from 7 to 6 on the west, from 6 to 5 on the north, and from 5 to the start. Read forwards, the route is south, south, east, east, paying 1 + 4 + 1 + 1 + 1 = 8, which the run printed.
The run also tried the driver's instinct, entering the cheaper of the two next districts each time. That goes east into the toll of 1, then east into 8 because 8 beats 9, then south twice: 1 + 1 + 8 + 9 + 1 = 20. The first move looked best and led into the expensive corner of the map. The table avoids that because each cell holds the best total over every route into it, not the best single step.
The pattern to take away: when a grid problem asks for the most or the least along a monotone route, keep the same table as for counting and change the sum into a maximum or minimum. The answer sits in the corner, and the route is read back by retracing, at each cell, the neighbour that won.
← → move through sections and cards