Sub topic 7
Minimum-Cost Paths
This chapter assumes you can already define a grid DP state, turn allowed moves into a recurrence, handle base cases at the edges, and choose a fill order. It builds directly on the path-counting chapter. You should also be comfortable with nested loops over 2D lists in Python and with Big-O notation.
The problem is this: you get an m × n grid of non-negative costs. You start at the top-left cell and must reach the bottom-right cell, moving only right or down. The cost of a path is the sum of every cell it visits, including the first and last cells. You want the smallest possible total.
From Counting to Optimizing
Path counting and minimum-cost paths share the same skeleton. Both use the same state and the same neighbors, and both fill the table in the same order. Only the operation that combines the neighbors changes.
| Aspect | Unique paths | Minimum-cost path |
|---|---|---|
| `dp[i][j]` means | number of paths from start to `(i, j)` | cheapest total cost from start to `(i, j)` |
| Combine predecessors with | `+` (sum) | `min` |
| Cell's own contribution | none | add `grid[i][j]` |
| Start cell value | `1` | `grid[0][0]` |
| Missing neighbor acts as | `0` (adds nothing) | `+∞` (never chosen) |
The last row of the table catches a lot of people. A missing neighbor has to be the identity element of the combining operation. For a sum the identity is 0. For min it is positive infinity, because min(x, ∞) = x. If you carry over the zero from path counting, the code will "find" free paths that come from outside the grid.
The State and the Recurrence
Define dp[i][j] as the minimum cost of any right/down path from (0, 0) to (i, j), counting both endpoints.
Any path into (i, j) arrives from exactly one of two cells: (i - 1, j) above or (i, j - 1) to the left. The cheapest path into (i, j) must therefore extend the cheapest path into one of those two cells. That gives the recurrence:
dp[0][0] = grid[0][0]dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j], treating an out-of-grid neighbor as+∞
This works because the problem has optimal substructure. Suppose 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 cheapest path to that cell. If it weren't, you could swap in a cheaper prefix and get a cheaper total, which contradicts the assumption.
Worked Example
Take this grid:
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 3 | 1 |
| row 1 | 1 | 5 | 1 |
| row 2 | 4 | 2 | 1 |
Fill the table row by row, left to right:
- Row 0 can only be reached from the left, so it holds running sums:
1, 4, 5. - Row 1:
dp[1][0] = 1 + 1 = 2.dp[1][1] = min(4, 2) + 5 = 7.dp[1][2] = min(5, 7) + 1 = 6. - Row 2:
dp[2][0] = 2 + 4 = 6.dp[2][1] = min(7, 6) + 2 = 8.dp[2][2] = min(6, 8) + 1 = 7.
| dp | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 4 | 5 |
| row 1 | 2 | 7 | 6 |
| row 2 | 6 | 8 | 7 |
The answer is 7, reached by the path 1 → 3 → 1 → 1 → 1. Recovering that route from the table is the topic of a later chapter. For now we only need the cost.
Implementation with Explicit Edges
The first version handles the top row and left column separately. Then every interior cell is guaranteed to have both neighbors.
def min_path_sum(grid):
if not grid or not grid[0]:
raise ValueError("grid must have at least one cell")
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): # top row: only reachable from the left
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, m): # left column: only reachable from above
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]])) # 7
print(min_path_sum([[5]])) # 5
print(min_path_sum([[1, 2, 3]])) # 6The 1×1, single-row, and single-column cases need no special code. The edge loops either do nothing or cover the whole grid.
Implementation with Infinity Padding
The second version adds an extra row and column of +∞, so the inner loop never needs a boundary check. One sentinel cell is set to 0 so that the start cell comes out right.
def min_path_sum_padded(grid):
m, n = len(grid), len(grid[0])
INF = float('inf')
dp = [[INF] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 0 # sentinel: makes dp[1][1] equal grid[0][0]
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1]
return dp[m][n]
print(min_path_sum_padded([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7Padding shifts every index by one. dp[i][j] now describes grid cell (i - 1, j - 1). Reading grid[i][j] by mistake is the most common bug in this style.
Common Errors
- Wrong identity for missing neighbors. Use
+∞withminand-∞withmax. Zero is only correct for sums. - Forgetting the start cell's cost. If you start with
dp[0][0] = 0, every answer is short bygrid[0][0]. Check whether the problem counts the starting cell. Most versions do. - Shared row references.
[[0] * n] * mcreatesmreferences to one list, so writing to one row changes all of them. Always use a list comprehension. - Overflow in other languages. In Java or C++,
INT_MAX + grid[i][j]overflows and becomes negative, whichminthen selects. Use a large finite sentinel such as10**9, or skip invalid neighbors explicitly. Python'sfloat('inf')does not have this problem.
Edge Cases and Variants
Negative costs. The recurrence stays correct even with negative cell values. Right/down moves can never return to a cell, so the dependency graph has no cycles, and no path can loop to collect a negative cell twice. The only change is that you can no longer assume the answer is at least grid[0][0].
More move types. If diagonal down-right moves are also allowed, add the third predecessor: min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + grid[i][j]. Row-major order still works, because (i-1, j-1) is filled before (i, j).
Maximum instead of minimum. For "collect the most coins," replace min with max and +∞ with -∞. If some cells are blocked, keep them at -∞ so that no path routes through them.
Moves in all four directions. Now the problem stops being a fill-order DP. Cell (i, j) can depend on (i + 1, j), which can depend on (i, j) again, so no row-by-row order satisfies every dependency. With non-negative costs, use Dijkstra's algorithm on the grid graph, which costs O(mn log(mn)). With negative costs and free movement, a "minimum" may not exist, because a path could loop forever.
| Allowed moves | Dependency graph | Method |
|---|---|---|
| right, down (optionally diagonal) | acyclic, follows row-major order | table DP, O(mn) |
| 4-directional, non-negative costs | cyclic | Dijkstra |
| 4-directional, strictly increasing values only | acyclic, but no fixed order | memoized DFS (later chapter) |
Complexity
Each of the mn cells does a constant amount of work, so the time is O(mn). The full table uses O(mn) space. Each row reads only itself and the row above, which means the table can be reduced to O(n). A later chapter covers that reduction, and why you might keep the full table so you can recover the route.
Exercise
Allow three moves: right, down, and diagonally down-right. What is the minimum path cost for the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]], and which path achieves it?
Show answer
5. The table rows are [1, 4, 5], [2, 6, 5], [6, 4, 5]. One optimal path is (0,0) → (1,0) → (2,1) diagonally → (2,2), with cost 1 + 1 + 2 + 1 = 5.
Exercise
In minpathsum_padded, what goes wrong if you delete the line dp[0][1] = 0?
Show answer
dp[1][1] becomes min(∞, ∞) + grid[0][0] = ∞. The infinity then spreads to every cell, so the function returns inf. The sentinel supplies a zero-cost "predecessor" for the start cell.
Exercise
A grid contains negative costs, and moves are restricted to right and down. Is the standard recurrence still correct? Would it stay correct if all four directions were allowed?
Show answer
With right/down moves it is still correct. Paths cannot revisit cells, so the dependencies stay acyclic and optimal substructure holds. With four directions the dependencies form cycles and the fill-order DP no longer applies. If a negative cycle is reachable, the minimum can be unbounded unless you forbid revisiting cells.