Sub topic 5
Counting Unique Paths
This chapter assumes you can write nested loops over a Python list of lists. It also assumes you have read the earlier chapters on defining a state, deriving a recurrence, handling base cases, and choosing a fill order. Here those four pieces come together in one complete solution.
The Problem
A robot stands in the top-left cell of an m by n grid. It may move only right or down. How many different routes lead it to the bottom-right cell?
Listing every route by hand works for tiny grids, but the number of routes grows very fast. A 10 by 10 grid already has 48,620 of them. Dynamic programming counts them without listing any.
Designing the Solution
State
dp[i][j] is the number of distinct right/down paths from (0, 0) to cell (i, j).
Recurrence
The last move into (i, j) came either from above, at (i - 1, j), or from the left, at (i, j - 1). A path through one of these neighbors can never be the same as a path through the other, so the counts add:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
Base Cases
Every cell in row 0 can be reached only by moving right, so each holds exactly one path. Every cell in column 0 can be reached only by moving down, so each also holds one path. If you set these edge cells to 1, the recurrence never reads outside the table.
Fill Order
Each cell depends on the cell above it and the cell to its left. Filling row by row, left to right, computes both of those before they are needed.
Implementation
def unique_paths(m, n):
dp = [[1] * n for _ in range(m)] # edges are already 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
print(unique_paths(3, 7)) # 28
print(unique_paths(3, 3)) # 6The loops start at index 1 because row 0 and column 0 are base cases. For a 3 by 3 grid, the finished table looks like this:
| row | col 0 | col 1 | col 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 1 | 2 | 3 |
| 2 | 1 | 3 | 6 |
Checking the Answer
Every route consists of exactly m - 1 down moves and n - 1 right moves, in some order. The number of routes is therefore the binomial coefficient C(m + n - 2, m - 1). You can use it to test your DP:
import math
for m, n in [(3, 7), (3, 3), (10, 10)]:
assert unique_paths(m, n) == math.comb(m + n - 2, m - 1)
print("all match")The formula only works for this exact problem. Once you add blocked cells or per-cell costs, the formula fails, but the DP still works with small changes.
Common Errors
- Setting only
dp[0][0] = 1while leaving the rest of the edges at 0. The first row and column then hold 0, and so does every cell computed from them. - Returning
dp[m][n]. The table has no rowm, so this raisesIndexError. The goal cell isdp[m - 1][n - 1]. - Starting both loops at 0 with no bounds checks. At
i = 0, the readdp[i - 1][j]becomesdp[-1][j]. Python treats that as the last row and returns the wrong number without raising any error.
Exercise
Fill the DP table for a 4 by 4 grid. What value is in the bottom-right cell, and does it match C(6, 3)?
Show answer
The rows are [1,1,1,1], [1,2,3,4], [1,3,6,10], [1,4,10,20]. The bottom-right cell is 20, and C(6, 3) = 20, so they match.
Exercise
Someone writes both loops starting at 0 and initializes the table with zeros except dp[0][0] = 1, with no boundary checks. Why is the result wrong even though no error is raised?
Show answer
When i = 0 or j = 0, the code reads dp[-1][j] or dp[i][-1]. Those are the last row and the last column, not missing neighbors. The extra values they add corrupt the edge counts, and the errors spread to every later cell.