Unique paths
medium 18 minA robot at the top-left of an m × n grid may only move right or down.
Video lesson · Chapter 1 of 6
Count routes without listing them
Unique paths in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
Set the edges. The top row and left column are all 1s: a straight line is the only way to reach them
Understand it
Start here
A robot, a grid and two moves
A robot stands on the top-left cell of a grid with rows and columns. It may only move right or down, one cell at a time, and it wants the bottom-right cell. How many different paths can it take? On a 3 × 3 grid the answer is 6; on a 3 × 7 grid it is 28.
Start: (0, 0)
The top-left cell. Rows are numbered to from the top, columns to from the left.
Moves: right or down
Never up, never left, so the robot can never revisit a cell and every path has the same length.
Goal: (m − 1, n − 1)
The bottom-right cell. Two paths are different if they differ in at least one move.
| 1D DP | 2D DP | |
|---|---|---|
| State | one index | two indices |
| Storage | an array dp[i] | a grid dp[r][c] |
| Depends on | dp[i - 1], dp[i - 2] | dp[r - 1][c], dp[r][c - 1] |
| Examples | climbing stairs, house robber | unique paths, minimum path sum, edit distance, LCS |
The recurrence
Every cell is above plus left
Look at the last move into a cell . It was either a move down from or a move right from . Every path is in exactly one of those two groups, so the counts add.
The recurrence
Working out one cell
From above
The robot was at and moved down. There are
dp[r - 1][c]such paths.From the left
The robot was at and moved right. There are
dp[r][c - 1]such paths.No third way
Up and left moves are not allowed, so no path can enter from below or from the right.
Base cases
The edges are all 1s
To reach a cell on the top row the robot never moved down, so it moved right every time: one path. To reach a cell on the left column it moved down every time: one path. These cells have no cell above or no cell to the left, so they are exactly where the recurrence needs a starting value.
| c = 0 | c = 1 | c = 2 | |
|---|---|---|---|
| r = 0 | 1 | 1 | 1 |
| r = 1 | 1 | ? | ? |
| r = 2 | 1 | ? | ? |
? cells are filled with the recurrence.Brute force
Plain recursion and its call tree
def paths(r, c): """Ways to reach (r, c) from (0, 0) moving right or down.""" if r == 0 or c == 0: return 1 return paths(r - 1, c) + paths(r, c - 1)def unique_paths(m, n): return paths(m - 1, n - 1)print(unique_paths(3, 3), unique_paths(3, 7)) # 6 28Call tree of f(2, 2) on a 3 × 3 grid
Leaves are paths
Complexity
Why brute force explodes
A quick upper bound
The tight rate for a square grid
| Grid | Paths | Brute-force calls | Memoised calls | Distinct cells |
|---|---|---|---|---|
| 3 × 3 | 6 | 11 | 9 | 9 |
| 3 × 7 | 28 | 55 | 25 | 21 |
| 10 × 10 | 48,620 | 97,239 | 163 | 100 |
| 16 × 16 | 155,117,520 | 310,235,039 | 451 | 256 |
Fix 1
Memoisation: each cell once
A memoised call
from functools import cachedef unique_paths_memo(m, n): memo = {} def paths(r, c): if r == 0 or c == 0: return 1 if (r, c) in memo: return memo[(r, c)] memo[(r, c)] = paths(r - 1, c) + paths(r, c - 1) return memo[(r, c)] return paths(m - 1, n - 1)def unique_paths_cached(m, n): @cache def paths(r, c): return 1 if r == 0 or c == 0 else paths(r - 1, c) + paths(r, c - 1) return paths(m - 1, n - 1)print(unique_paths_memo(10, 10), unique_paths_cached(23, 12)) # 48620 193536720functools.cache.Fix 2
Bottom-up: fill the table
- 1Create gridan m × n table
- 2Init edgesrow 0 and column 0 = 1
- 3Fill tabletop + left, row by row
- 4Resultdp[m - 1][n - 1]
def unique_paths(m, n): dp = [[0] * n for _ in range(m)] # one separate list per row for c in range(n): dp[0][c] = 1 # top row for r in range(m): dp[r][0] = 1 # left column for r in range(1, m): for c in range(1, n): dp[r][c] = dp[r - 1][c] + dp[r][c - 1] return dp[m - 1][n - 1]for row in [[unique_paths(r, c) for c in range(1, 6)] for r in range(1, 6)]: print(row)| c = 0 | c = 1 | c = 2 | |
|---|---|---|---|
| r = 0 | 1 | 1 | 1 |
| r = 1 | 1 | 2 = 1 + 1 | 3 = 1 + 2 |
| r = 2 | 1 | 3 = 2 + 1 | 6 = 3 + 3 |
Space
One row is enough
Row only reads row and itself. So keep one array row of length . Just before row[c] is updated it still holds the old value, the cell above; row[c - 1] was already updated, the cell to the left. One line does the whole job: row[c] += row[c - 1].
Turning row 1 into row 2 in place (3 × 7)
def unique_paths(m, n): if n > m: m, n = n, m # paths(m, n) == paths(n, m): keep the row short row = [1] * n # the top row for _ in range(1, m): for c in range(1, n): row[c] += row[c - 1] # above (old) + left (new) return row[n - 1]print(unique_paths(3, 7), unique_paths(7, 3), unique_paths(10, 10)) # 28 28 48620The math
Count the moves: C(m + n − 2, m − 1)
Every path makes exactly downs and rights, moves in all; only the order differs. Writing a path as a string like DRDR, a path is fixed once you choose which positions hold the Ds. So the number of paths is a binomial coefficient.
The closed form
Worked examples
math.comb does it exactly.The table is Pascal's triangle
Variant
Unique Paths II: rocks on the grid
One cell, with obstacles
| c = 0 | c = 1 | c = 2 | c = 3 | |
|---|---|---|---|---|
| r = 0 | 1 | 1 | # 0 | 0 |
| r = 1 | 1 | 2 | 2 | 2 |
| r = 2 | 1 | # 0 | 2 | 4 |
| r = 3 | 1 | 1 | 3 | 7 |
def unique_paths_with_obstacles(grid): n = len(grid[0]) row = [0] * n row[0] = 1 # one way to stand at the start (if it is open) for cells in grid: for c in range(n): if cells[c] == 1: row[c] = 0 # rock: nothing reaches or passes through it elif c > 0: row[c] += row[c - 1] # above (old) + left (new) return row[n - 1]print(unique_paths_with_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2print(unique_paths_with_obstacles([[0, 0, 1, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]])) # 7print(unique_paths_with_obstacles([[1]])) # 0grid[r][c] == 1 marks a rock. One rolling row is enough here too.Choosing
Which approach, and the grid DP family
| Approach | Time | Space | Easy to explain | Handles rocks |
|---|---|---|---|---|
| Plain recursion | stack | Yes | Yes, but too slow | |
| Memoised recursion | Yes | Easy | ||
| 2D table | Yes | Easy | ||
| One rolling row | Mostly | Easy | ||
| Binomial formula | Needs the counting idea | No |
Which version to write
Minimum path sum
Each cell has a cost. Replace the sum by a minimum:
dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1]).Four directions
If the robot may also go up or left, paths can loop and the table has no fill order. Use BFS or DFS with a visited set instead; see matrix BFS.
Track the actual path
Store which neighbour each cell came from (or walk back through the table choosing a neighbour with a nonzero count) to rebuild a path.
Two strings as a grid
Edit distance and longest common subsequence fill a table indexed by two string positions with the same above, left and diagonal pattern.
One rolling row
- memory: 7 cells instead of 21 for 3 × 7.
- Same time and the same answers.
- Works with rocks too.
Full 2D table
- memory.
- But easier to read, debug and print.
- Needed if you must rebuild the path afterwards.
Recap
Key takeaways
Key points
- dp[r][c] = number of ways to reach (r, c); the answer is dp[m - 1][n - 1].
- The last move came from above or from the left, so dp[r][c] = dp[r - 1][c] + dp[r][c - 1].
- Top row and left column are 1; the start counts as 1, so a 1 × 1 grid has 1 path.
- Plain recursion makes 2 × paths − 1 calls: exponential. Memoisation or a table gives O(m·n).
- One rolling row, updated left to right with row[c] += row[c - 1], needs only O(min(m, n)) space.
- Closed form: C(m + n − 2, m − 1), choosing which moves are downs. 3 × 3 = 6, 3 × 7 = 28.
- Rocks are cells forced to 0; never pre-fill the edges with 1s when rocks are possible.