Sub topic 5
Counting Unique Paths
This chapter turns the state, recurrence, base-case, and fill-order ideas from earlier chapters into a complete working solution. It assumes you can read Python with nested loops and 2D lists, know row/column indexing, and are comfortable with recursion and Big-O notation.
The Problem
A robot stands in the top-left cell of an m by n grid. On each step it can move one cell right or one cell down. How many distinct routes reach the bottom-right cell?
For a 3-row, 7-column grid, the answer is 28. Listing routes by hand stops working almost at once, because the count grows exponentially with grid size. Dynamic programming gets the answer in one pass over the cells.
State, Recurrence, and Base Cases
The three design decisions from earlier chapters become concrete here.
| Decision | Choice for unique paths |
|---|---|
| State | `dp[i][j]` = number of distinct routes from `(0, 0)` to `(i, j)` |
| Recurrence | `dp[i][j] = dp[i-1][j] + dp[i][j-1]` |
| Base cases | `dp[0][j] = 1` and `dp[i][0] = 1` |
| Fill order | Row by row, left to right |
| Answer | `dp[m-1][n-1]` |
The recurrence follows from the moves. Every route into (i, j) makes its last step from either the cell above or the cell to the left. Those two groups of routes do not overlap, because their last steps differ. Together they cover every route. So the counts add.
The base cases come from the edges. A cell in the top row can only be reached by moving right the whole way, so it has exactly one route. The same reasoning gives one route to every cell in the left column. The start cell (0, 0) also counts as 1: one route, the empty one, of length zero. That 1 is the seed every other count grows from.
Bottom-Up Implementation
def unique_paths(m, n):
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
dp[i][j] = 1
else:
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(1, 1)) # 1
print(unique_paths(3, 3)) # 6Row-major order (row by row, left to right) works here because both dependencies, the cell above and the cell to the left, are always filled before the current cell. The i == 0 or j == 0 branch handles the edges, so the code never reads dp[-1][j]. In Python, dp[-1][j] would not raise an error. It would quietly read the last row instead.
Watching the Table Fill
Here is the full table for m = 3, n = 7:
| row \ col | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 2 | 1 | 3 | 6 | 10 | 15 | 21 | 28 |
Every interior entry is the sum of the entry above it and the entry to its left. Row 1 counts up by one at each step. Row 2 holds the triangular numbers. This is Pascal's triangle turned on its side, and that leads straight to a closed form.
Checking Against the Closed Form
Every route makes exactly m - 1 down moves and n - 1 right moves, in some order. A route is fully determined by which of the m + n - 2 steps are the down moves. So the count is the binomial coefficient C(m + n - 2, m - 1).
The closed form makes a good test oracle. Here is a test that compares the DP, the formula, and a brute-force enumeration:
import math
def unique_paths(m, n):
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
def brute_force(i, j, m, n):
if i == m - 1 and j == n - 1:
return 1
total = 0
if i + 1 < m:
total += brute_force(i + 1, j, m, n)
if j + 1 < n:
total += brute_force(i, j + 1, m, n)
return total
for m in range(1, 7):
for n in range(1, 7):
expected = math.comb(m + n - 2, m - 1)
assert unique_paths(m, n) == expected
assert brute_force(0, 0, m, n) == expected
print("all sizes agree")If the formula exists, why use DP? Because the formula breaks the moment the problem changes. Add a blocked cell, a diagonal move, or a per-cell weight, and no simple binomial applies. The DP recurrence absorbs those changes with small edits. The next chapters rely on that.
A Top-Down View of the Same Recurrence
The same recurrence can run as recursion with a cache:
from functools import lru_cache
def unique_paths(m, n):
@lru_cache(maxsize=None)
def ways(i, j):
if i == 0 or j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
return ways(m - 1, n - 1)
print(unique_paths(3, 7)) # 28Without lru_cache, this is the brute-force recursion, and it takes exponential time. With the cache, each (i, j) is computed once. A later chapter compares the two styles in detail. For now, notice that both versions use the same state, recurrence, and base cases. Only the evaluation order changes.
Common Errors
Aliased rows
dp = [[0] * 3] * 2
dp[0][0] = 5
print(dp) # [[5, 0, 0], [5, 0, 0]]The outer * 2 copies a reference to the same inner list, so writing to one row writes to all of them. A path-counting table built this way gives wrong answers with no error. Always build rows with a comprehension: [[0] * n for _ in range(m)].
Swapping rows and columns
For counting, unique_paths(m, n) == unique_paths(n, m), so passing the dimensions in the wrong order still gives the right answer. The bug only appears later, when a non-square grid of weights or obstacles is indexed as grid[j][i]. Pick one convention and use it everywhere: i for rows, j for columns, m = len(grid), n = len(grid[0]).
Off-by-one on the answer
The table has indices 0..m-1 and 0..n-1. Returning dp[m][n] raises IndexError. In a padded table, where the size is (m+1) x (n+1) with a border of zeros, dp[m][n] is the correct answer. Know which layout you are using.
Forgetting the seed in a padded table
If you pad with zeros to avoid edge checks, every cell starts at 0, and sums of zeros stay 0. You must plant one 1, for example dp[0][1] = 1. Then dp[1][1] picks it up from above and the counts grow from there:
def unique_paths_padded(m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m][n]
print(unique_paths_padded(3, 7)) # 28Degenerate inputs
A 1 by 1 grid has one route, the empty one. Both implementations return 1. A grid with zero rows or columns has no start cell. grid[0] would fail, and so would the table code. Decide on a return value (usually 0) and guard against it explicitly if your inputs allow it.
Overflow Outside Python
Python integers have no fixed size, so the counts never overflow. In Java, C++, or Rust they will. A 34 by 34 grid gives C(66, 33) ≈ 7.2 × 10^18, which still fits in a signed 64-bit integer. A 35 by 35 grid gives C(68, 34) ≈ 2.8 × 10^19, which overflows both signed and unsigned 64-bit types. This is why contest problems often ask for the count modulo 10^9 + 7. In that case, apply % MOD after every addition:
MOD = 10**9 + 7
def unique_paths_mod(m, n):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD
return dp[m - 1][n - 1]
print(unique_paths_mod(100, 100)) # 690285631This version also shows another way to set the base cases. Filling the whole table with 1 sets both edges at once, and the loops then start at index 1.
Exercises
Exercise
In the 3 by 7 table, dp[2][3] is 10. Explain the value using the recurrence, then confirm it with the closed form.
Show answer
dp[2][3] = dp[1][3] + dp[2][2] = 4 + 6 = 10. The cell (2, 3) needs 2 down moves and 3 right moves, so C(5, 2) = 10.
Exercise
Suppose the robot may also move diagonally down-right in one step. Write the new recurrence and compute the number of routes in a 3 by 3 grid.
Show answer
dp[i][j] = dp[i-1][j] + dp[i][j-1] + dp[i-1][j-1] for interior cells, and edge cells stay 1. Row 1 becomes 1, 3, 5. Row 2 becomes 1, 5, 13. The answer is 13. The closed form C(4, 2) = 6 no longer applies, but the DP needed only one extra term.
Exercise
A teammate writes dp = [[1] n] m and then runs the loops from index 1. For m = 3 and n = 3, what does the function return, and why?
Show answer
All three rows are the same list, so the table effectively has one row. With i = 1, dp[i-1][j] and dp[i][j-1] both read that same list. Row 1 updates it to [1, 2, 3]. Row 2 then computes dp[1] = 3 + 1 = 4 and dp[2] = 3 + 4 = 7, so the function returns 7 instead of 6. The fix is [[1] * n for _ in range(m)].