Sub topic 7
Minimum-Cost Paths
This chapter assumes you can already count unique paths with a 2D table, and that you are comfortable with nested loops and row/column indexing in Python. Here the table stores something different. Each entry holds the cheapest total cost to reach a cell, where the count-based version stored a number of ways.
The Problem
You get an m x n grid of non-negative integers. You start at the top-left cell and finish at the bottom-right cell, moving only right or down. The cost of a path is the sum of every cell it visits, including both endpoints. Find the smallest possible cost.
Defining the State and Recurrence
Let dp[i][j] be the minimum cost of any path from (0, 0) to (i, j), including grid[i][j] itself.
The allowed moves are right and down, so there are only two ways to enter cell (i, j): from above at (i-1, j) or from the left at (i, j-1). The best path into (i, j) must extend the cheaper of those two best paths:
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]The recurrence has the same shape as path counting. The only change is the combining step: counting adds the two neighbors, and this version takes their minimum and then adds the current cell's cost.
Base Cases
The edges need special handling because each edge cell has only one predecessor:
dp[0][0] = grid[0][0]- First row:
dp[0][j] = dp[0][j-1] + grid[0][j], because these cells can only be reached from the left. - First column:
dp[i][0] = dp[i-1][0] + grid[i][0], because these cells can only be reached from above.
Implementation
def min_path_sum(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for j in range(1, n):
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[m - 1][n - 1]
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7The loops fill the table row by row, left to right. That order guarantees the cell above and the cell to the left are both finished before they are read.
Tracing the Example
| grid | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 3 | 1 |
| row 1 | 1 | 5 | 1 |
| row 2 | 4 | 2 | 1 |
| dp | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 4 | 5 |
| row 1 | 2 | 7 | 6 |
| row 2 | 6 | 8 | 7 |
For example, dp[1][2] = min(dp[0][2], dp[1][1]) + 1 = min(5, 7) + 1 = 6.
Common Errors
- Initializing the edges to 0. The first row and first column must hold running sums. If they hold zeros, edge cells look free and the answer comes out too low.
- Adding the cost to each neighbor separately.
min(dp[i-1][j] + c, dp[i][j-1] + c)gives the right answer, butmin(dp[i-1][j], dp[i][j-1] + c)does not. Addgrid[i][j]once, after taking the minimum. - Padding with zeros. If you add an extra border row and column to skip edge checks, fill it with
float('inf'), not 0. The one exception is the cell that feeds the start, which must be 0.
The algorithm takes O(mn) time and O(mn) space. Later chapters reduce the table to one row and recover the route itself.
Exercise
What is the minimum path sum for grid [[1, 2, 3], [4, 5, 6]], and what is the filled dp table?
Show answer
The answer is 12. The dp table is row 0 = [1, 3, 6] and row 1 = [5, 8, 12]. The bottom-right cell is min(6, 8) + 6 = 12, from the path right, right, down: 1+2+3+6.
Exercise
If cells could hold negative costs but moves were still only right and down, would the recurrence still work?
Show answer
Yes. Right/down moves cannot form cycles, so every cell's predecessors are final before the cell is computed. Negative values do not break the recurrence.