Sub topic 11
Recovering the Optimal Path
This chapter assumes you have already built the minimum-cost path table and know that dp[i][j] holds the cheapest cost to reach cell (i, j) moving only right or down. It also assumes you are comfortable with 2D indexing and nested loops.
The table tells you how much the best path costs. Often you also need to know which cells that path visits. You can recover the path from the filled table by walking backward from the goal.
Why the Table Already Contains the Path
Every cell's value came from one of its two predecessors:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
The predecessor that won the min lies on an optimal path into (i, j). If you start at the goal and repeatedly step to the predecessor with the smaller value, you retrace one optimal route back to the start. Each step uses only values already in the table, so recovering the path costs no extra DP work.
The Implementation
You must keep the full 2D table here. A rolling single row throws away the earlier rows that the backtrack needs to read.
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)])The filled table for this grid is:
| row | col 0 | col 1 | col 2 |
|---|---|---|---|
| 0 | 1 | 4 | 5 |
| 1 | 2 | 7 | 6 |
| 2 | 6 | 8 | 7 |
The backtrack starts at 7. Above it is 6 and to its left is 8, so it moves up. From (1, 2) the cell above holds 5 and the cell to the left holds 7, so it moves up again. On the top row the only option is to move left, twice.
Common Errors
- Skipping the edge checks. On row 0 there is no cell above. Without the
i == 0branch,dp[-1][j]silently reads the last row, because Python allows negative indices. - Forgetting to reverse. The walk collects cells from goal to start.
- Expecting one unique path. When two predecessors tie,
<=always picks "up". The result is optimal, but other optimal paths may exist. - Re-deriving with a different recurrence. The backtrack must mirror the exact rule used to fill the table, or it can step onto a cell that does not lead to the start optimally.
Cost
Filling the table takes O(mn) time and space. The backtrack takes O(m + n) steps, because each step reduces i or j by one.
Exercise
You have switched to the one-row space-optimized version of minpathsum. Can you still recover the path, and what is the cheapest way to do it?
Show answer
Not from the single row, because the earlier rows have been overwritten. Keep an m-by-n table of choices (one bit per cell is enough: up or left) while you fill the row, then follow those choices back from the goal. This still needs O(mn) memory, but much less than storing full costs.
Exercise
For grid [[1, 1], [1, 1]], which path does the code return, and why?
Show answer
It returns [(0, 0), (1, 0), (1, 1)]. At (1, 1) both predecessors hold 2, and the tie-break <= chooses up, which moves to (1, 0). From the left column the walk can only move up, to (0, 0).