Full answer
Problem
A robot starts at the top-left of an m x n grid and moves only right or down. Return the number of distinct paths to the bottom-right cell. Then solve it when some cells (marked 1) are blocked.
Example: a 3 x 7 grid has 28 paths; a 3 x 2 grid has 3. The grid [[0,0,0],[0,1,0],[0,0,0]] has 2 paths.
Constraints: 1 <= m, n <= 100; answers fit in a 64-bit integer for the classic limits.
Brute force
Recursively try moving right and down from each cell and count arrivals: O(2^(m+n)), because cells are revisited along many paths.
Optimal approach
row = [1] * n for the first row. For each later row, for j from 1 to n - 1: row[j] += row[j - 1] (the old row[j] is the value from above, row[j - 1] is the value from the left).
With obstacles: start row = [1, 0, ..., 0]; for every row, set row[j] = 0 at blocked cells, else add row[j - 1] when j > 0.
Closed form (no obstacles): choose which m - 1 of the m + n - 2 moves are downs: C(m + n - 2, m - 1).
Why it works
Every path into a cell arrives from above or from the left, and those two groups do not overlap, so their counts add. Filling row by row, left to right, guarantees both neighbours are ready. A blocked cell has no paths through it, so it contributes 0 to its neighbours. In the closed form, a path is just a sequence of m - 1 downs and n - 1 rights in some order.
Complexity
O(m * n) time and O(n) space for the DP; O(min(m, n)) arithmetic steps for the binomial.
Code
import random
from math import comb
def unique_paths(m, n):
"""Right/down moves on an m x n grid. One rolling row: O(m * n) time, O(n) space."""
row = [1] * n
for _ in range(1, m):
for j in range(1, n):
row[j] += row[j - 1] # from above (old row[j]) + from the left
return row[-1]
def unique_paths_math(m, n):
"""Choose which of the m+n-2 moves are downs: C(m+n-2, m-1)."""
return comb(m + n - 2, m - 1)
def unique_paths_obstacles(grid):
"""1 marks a blocked cell."""
n = len(grid[0])
row = [0] * n
row[0] = 1
for r in grid:
for j in range(n):
if r[j]:
row[j] = 0
elif j:
row[j] += row[j - 1]
return row[-1]
def brute(grid, r=0, c=0):
m, n = len(grid), len(grid[0])
if r >= m or c >= n or grid[r][c]:
return 0
if (r, c) == (m - 1, n - 1):
return 1
return brute(grid, r + 1, c) + brute(grid, r, c + 1)
if __name__ == "__main__":
assert unique_paths(3, 7) == 28 and unique_paths(3, 2) == 3 and unique_paths(1, 1) == 1
assert all(unique_paths(m, n) == unique_paths_math(m, n) for m in range(1, 12) for n in range(1, 12))
assert unique_paths_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 2
assert unique_paths_obstacles([[1]]) == 0 and unique_paths_obstacles([[0, 1], [1, 0]]) == 0
rng = random.Random(84)
for _ in range(500):
m, n = rng.randint(1, 6), rng.randint(1, 6)
g = [[int(rng.random() < 0.2) for _ in range(n)] for _ in range(m)]
assert unique_paths_obstacles(g) == brute(g)
print("all tests passed")Save as b84_unique_paths.py and run python3 b84_unique_paths.py. It prints all tests passed (Python 3.13.5).
Edge cases
1 x 1 grid (1 path). A single row or column (1 path). Blocked start or end (0). A wall that cuts the grid (0). Large grids where counts overflow 64 bits (Python is exact; elsewhere use modular arithmetic or big integers).
Pattern
Grid DP where each cell combines its predecessors. Related: minimum path sum (min instead of sum), dungeon game (fill backwards from the end), cherry pickup, and counting lattice paths with combinatorics.
import random
from math import comb
def unique_paths(m, n):
"""Right/down moves on an m x n grid. One rolling row: O(m * n) time, O(n) space."""
row = [1] * n
for _ in range(1, m):
for j in range(1, n):
row[j] += row[j - 1] # from above (old row[j]) + from the left
return row[-1]
def unique_paths_math(m, n):
"""Choose which of the m+n-2 moves are downs: C(m+n-2, m-1)."""
return comb(m + n - 2, m - 1)
def unique_paths_obstacles(grid):
"""1 marks a blocked cell."""
n = len(grid[0])
row = [0] * n
row[0] = 1
for r in grid:
for j in range(n):
if r[j]:
row[j] = 0
elif j:
row[j] += row[j - 1]
return row[-1]
def brute(grid, r=0, c=0):
m, n = len(grid), len(grid[0])
if r >= m or c >= n or grid[r][c]:
return 0
if (r, c) == (m - 1, n - 1):
return 1
return brute(grid, r + 1, c) + brute(grid, r, c + 1)
if __name__ == "__main__":
assert unique_paths(3, 7) == 28 and unique_paths(3, 2) == 3 and unique_paths(1, 1) == 1
assert all(unique_paths(m, n) == unique_paths_math(m, n) for m in range(1, 12) for n in range(1, 12))
assert unique_paths_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 2
assert unique_paths_obstacles([[1]]) == 0 and unique_paths_obstacles([[0, 1], [1, 0]]) == 0
rng = random.Random(84)
for _ in range(500):
m, n = rng.randint(1, 6), rng.randint(1, 6)
g = [[int(rng.random() < 0.2) for _ in range(n)] for _ in range(m)]
assert unique_paths_obstacles(g) == brute(g)
print("all tests passed")Rolling-row counts, the binomial closed form, and the obstacle version cross-checked against plain recursion on random small grids.
Complexity
Time: O(m * n). Space: O(n). The binomial needs O(min(m, n)) multiplications.
By level
Fresher: Fills the table by adding the cell above and the cell to the left, and explains why. Handles blocked cells by setting them to 0.
Mid: Reduces space to one row, derives the binomial formula, and explains why it fails with obstacles. Adapts the DP to minimum path sum.
Senior: Computes large answers with modular binomials and factorial tables, and discusses inclusion-exclusion for a few obstacles on huge grids. Relates grid DP fill order to dependency direction in more complex problems.
Key points
- ways(cell) = ways(up) + ways(left)
- One row is enough
- Blocked cells contribute 0
- Closed form C(m+n-2, m-1)
- Fill order guarantees dependencies are ready
Common mistakes
- Initializing the first column wrong when obstacles appear
- Forgetting that a blocked start makes the answer 0
- Using the closed form when obstacles exist
- Integer overflow in fixed-width languages
Follow-ups
- How do you find the minimum path sum instead?
- What if the robot may also move diagonally?
- How would you compute the answer modulo 10^9 + 7 for a 10^5 x 10^5 grid?
Tips
- Show the 2 x 2 or 3 x 3 table by hand
- Mention the combinatorial formula
- Handle obstacles in the first row and column
Evaluation rubric
- Correct recurrence
- Space optimization
- Correct obstacle handling
- Knows the closed form