Sub topic 11
Recovering the Optimal Path
This chapter assumes you have already built the 2D minimum-cost table from the "Minimum-Cost Paths" chapter. You should be comfortable with nested loops, row/column indexing, and the recurrence dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j].
A filled DP table tells you the cost of the best path, but not which cells the path uses. Many real tasks need the route itself: a robot needs the moves, a diff tool needs the edits, and a game needs the walk to animate. This chapter shows two ways to recover the route, explains why tie-breaking matters, and covers what space optimization costs you.
The Core Idea: Every Value Remembers Its Origin
Each entry dp[i][j] was produced by choosing one predecessor, either the cell above or the cell to the left. The table does not store that choice, but you can work it out again. If dp[i][j] came from the cell above, then:
dp[i][j] == dp[i-1][j] + grid[i][j]Because the recurrence takes the minimum, the predecessor actually chosen is the one with the smaller dp value. So you start at the goal and repeatedly step to the cheaper predecessor until you reach the start. That gives the path in reverse, and you reverse it at the end.
This works because of optimal substructure. If the best path to (i, j) passes through (i-1, j), then the part of it that ends at (i-1, j) must itself be a best path to (i-1, j). Each backward step therefore lands on a cell whose own dp value is also explained by an optimal choice.
Method 1: Backtrack Through the Filled Table
The first method keeps the full table and recomputes each decision on the way back.
def min_path_with_route(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
elif i == 0:
dp[i][j] = dp[i][j - 1] + grid[i][j]
elif j == 0:
dp[i][j] = dp[i - 1][j] + grid[i][j]
else:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
path = []
i, j = m - 1, n - 1
while True:
path.append((i, j))
if i == 0 and j == 0:
break
if i == 0:
j -= 1
elif j == 0:
i -= 1
elif dp[i - 1][j] <= dp[i][j - 1]:
i -= 1
else:
j -= 1
path.reverse()
return dp[m - 1][n - 1], path
print(min_path_with_route([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
# (7, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])Here is the filled table for the example grid:
| row \ col | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 1 | 4 | 5 |
| 1 | 2 | 7 | 6 |
| 2 | 6 | 8 | 7 |
The walk starts at (2, 2) with value 7. The cell above holds 6 and the cell to the left holds 8, so it moves up to (1, 2). There, the cell above holds 5 and the left neighbour holds 7, so it moves up again to (0, 2). On the top row the only option is left, which takes it to (0, 1) and then (0, 0). Reversing the list gives the route 1 → 3 → 1 → 1 → 1, which sums to 7.
The backtracking loop must handle the same boundaries as the fill loop. On the top row there is no cell above, and in the left column there is no cell to the left. If you skip those checks, dp[i - 1][j] with i == 0 reads dp[-1][j]. Python's negative indexing returns the last row without raising an error, and the path quietly goes wrong.
Method 2: Store Parent Pointers During the Fill
The second method records each decision when it is made, so the backward walk never has to recompute anything. This matters when the recurrence is expensive to evaluate again, or when it has many candidate predecessors, as in edit distance with three moves or problems with custom move sets.
def min_path_with_parents(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
parent = [[None] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
continue
candidates = []
if i > 0:
candidates.append((dp[i - 1][j], (i - 1, j)))
if j > 0:
candidates.append((dp[i][j - 1], (i, j - 1)))
best_cost, best_cell = min(candidates)
dp[i][j] = best_cost + grid[i][j]
parent[i][j] = best_cell
path = []
cell = (m - 1, n - 1)
while cell is not None:
path.append(cell)
cell = parent[cell[0]][cell[1]]
path.reverse()
return dp[m - 1][n - 1], path
print(min_path_with_parents([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
# (7, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])The start cell's parent is None, which ends the loop. Note that min(candidates) compares tuples, so on a cost tie it breaks the tie by comparing coordinates. That is a hidden tie-breaking rule, covered in the next section.
| Aspect | Recompute from table | Parent pointers |
|---|---|---|
| Extra memory | None beyond `dp` | One pointer per cell |
| Backtrack cost per step | Re-evaluates the recurrence | O(1) lookup |
| Risk of mismatch | Backtrack logic can disagree with fill logic | Decision is recorded once |
| Best fit | Simple recurrences with two moves | Many moves, or costly transitions |
Both methods take O(m·n) time to fill the table and O(m + n) time to walk back, because each step reduces i + j by one.
Ties and Which Path You Get
When the two predecessors have equal cost, more than one optimal path exists. Both are correct, but which one your code returns depends on the comparison. With <=, the backtrack prefers moving up, so going forward the path tends to run right along the top first and come down late. With <, it prefers moving left, and the path comes down early.
This matters in tests. If an expected-output test was written for one tie-breaking rule, a correct solution using the other rule will fail it. When a problem says "return any optimal path," check your answer by verifying properties instead of comparing to one fixed path:
- The path starts at
(0, 0)and ends at(m-1, n-1). - Each step moves exactly one cell right or one cell down.
- The sum of
gridvalues along the path equalsdp[m-1][n-1].
def is_valid_optimal(grid, cost, path):
m, n = len(grid), len(grid[0])
if path[0] != (0, 0) or path[-1] != (m - 1, n - 1):
return False
for (a, b), (c, d) in zip(path, path[1:]):
if (c - a, d - b) not in ((1, 0), (0, 1)):
return False
return sum(grid[i][j] for i, j in path) == cost
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
cost, path = min_path_with_route(grid)
print(is_valid_optimal(grid, cost, path)) # TrueIf you need every optimal path, a single backtrack is not enough. Branch at each tie and recurse on both predecessors. The number of optimal paths can grow exponentially in the grid size, so only list them all when the output size is known to be small.
Reconstruction and Rolling Arrays Conflict
The "Shrinking the Table to One Row" chapter reduced memory to O(n) by keeping one row. That optimization discards the values that backtracking needs. Once row i is overwritten, you can no longer tell whether a cell in it was reached from above or from the left.
You have a few options:
- Keep the full O(m·n)
dptable. This is the simplest choice and is usually fine for grids up to a few million cells. - Keep a rolling
dprow but store a compact choice table: one bit per cell (0 for "from above", 1 for "from left"). Memory stays O(m·n) but shrinks by roughly a factor of 64 compared with Python integers in a list of lists. Abytearrayor a bitset brings it close to that. - Use divide and conquer, as Hirschberg's algorithm does for sequence alignment. Compute the cost forward to the middle row and backward from the goal to the middle row, find the cell where the best path crosses the middle, then recurse on the two halves. This recovers the path in O(n) extra space at roughly twice the time.
Common Errors
- Forgetting to reverse. The walk produces goal-to-start order. Return
path[::-1]or callpath.reverse(). - Off-by-one with padded tables. If your
dphas an extra zero row and column, table index(i, j)corresponds to grid cell(i-1, j-1). Convert before appending to the path. - Backtracking on the wrong criterion. For minimum cost, step to the smaller predecessor. For maximum-value problems, step to the larger one. Copying a minimum-cost backtrack into a maximum-value problem produces a valid but suboptimal path.
- Stopping condition misses the start. Loop until you have appended
(0, 0), not untili == 0orj == 0. Stopping at the first edge you reach drops the cells between that point and the start.
Exercise
Run minpathwith_route on [[1, 1], [1, 1]]. What path does it return, and what single change to the backtrack loop makes it return the other optimal path?
Show answer
The table is [[1, 2], [2, 3]]. At (1, 1) both predecessors hold 2, and the <= comparison moves up, so the result is (3, [(0, 0), (0, 1), (1, 1)]). Changing dp[i - 1][j] <= dp[i][j - 1] to dp[i - 1][j] < dp[i][j - 1] makes ties move left, which gives (3, [(0, 0), (1, 0), (1, 1)]).
Exercise
You have the one-row minpathsum from an earlier chapter and now must also return the route for a 2000 × 2000 grid. Describe a modification that keeps the O(n) dp row and records just enough to reconstruct the path. How much extra memory does it use?
Show answer
While filling each cell, record which predecessor won in a choice table: one bit per cell, 0 for "from above" and 1 for "from left", with the top row forced to "left" and the left column forced to "up". Then backtrack from (m-1, n-1) by reading the bits. Stored as a bitset, that is 2000 × 2000 = 4,000,000 bits, about 500 KB. A bytearray with one byte per cell takes about 4 MB.
Exercise
Why does the backtrack loop always finish in exactly m + n - 1 appended cells for a right/down grid?
Show answer
Each step moves either up or left, so it lowers i + j by exactly one. The walk starts at i + j = (m - 1) + (n - 1) and stops at 0. That is m + n - 2 steps, and counting the starting cell gives m + n - 1 cells.