Count the routes across an obstacle-free rectangular grid when movement is restricted to right or down.
Problem
Input. Positive integers rows and cols specifying the grid dimensions.
Output. Return the number of distinct move sequences from the top-left cell to the bottom-right cell.
Rules. Each move advances exactly one cell right or one cell down, remaining inside the grid. There are no obstacles, diagonal moves, or backward moves. Different move orders count separately. A one-cell grid has one route: take no moves.
Example. A grid with 3 rows and 2 columns returns 3.
Its routes are right-down-down, down-right-down, and down-down-right. A 3-by-7 grid returns 28.
Picture
Every path enters an interior cell through exactly one final direction. The two incoming groups are disjoint, so their counts add.
Each top-row and first-column cell has exactly one route.
Problem trace
Read above from the previous row and left from the row being updated
- start/current
- (0, 0)
- rolling row
- [1,1,1]
- column 0 / row 0
- 1
- current
- (0, 0)→(1, 1)
- above
- not shown→(0, 1)
- left
- not shown→(1, 0)
- current
- (1, 1)→(1, 2)
- above
- (0, 1)→(0, 2)
- left
- (1, 0)→(1, 1)
- current
- (1, 2)→(2, 1)
- above
- (0, 2)→(1, 1)
- left
- (1, 1)→(2, 0)
- current
- (2, 1)→(2, 2)
- above
- (1, 1)→(1, 2)
- left
- (2, 0)→(2, 1)
- Recognize it
- Use it when movement forms an acyclic grid and every path into a cell must arrive through a small fixed set of predecessor directions such as above and left.
- Keep true
- During a row sweep, ways[col] before update is the count from above and ways[col-1] after update is the count from the left; their sum is the current cell count.
- Reuse it
- When dependencies come from the previous row and current row prefix, sweep in the direction that preserves both and compress the grid to one mutable row.
Reference drawing
Problem trace
Read above from the previous row and left from the row being updated
Execution trace
- start/current
- (0, 0)
- rolling row
- [1,1,1]
- column 0 / row 0
- 1
- current
- (0, 0)→(1, 1)
- above
- not shown→(0, 1)
- left
- not shown→(1, 0)
- current
- (1, 1)→(1, 2)
- above
- (0, 1)→(0, 2)
- left
- (1, 0)→(1, 1)
- current
- (1, 2)→(2, 1)
- above
- (0, 2)→(1, 1)
- left
- (1, 1)→(2, 0)
- current
- (2, 1)→(2, 2)
- above
- (1, 1)→(1, 2)
- left
- (2, 0)→(2, 1)
- Recognize it
- Use it when movement forms an acyclic grid and every path into a cell must arrive through a small fixed set of predecessor directions such as above and left.
- Keep true
- During a row sweep, ways[col] before update is the count from above and ways[col-1] after update is the count from the left; their sum is the current cell count.
- Reuse it
- When dependencies come from the previous row and current row prefix, sweep in the direction that preserves both and compress the grid to one mutable row.
Code
Before each update, ways[col] still counts routes to the cell above.
ways[col - 1] already counts routes to the left cell in the current row. Sweep left to right to retain both meanings.
def unique_paths(rows: int, cols: int) -> int:
ways = [1] * cols
for _ in range(1, rows):
for col in range(1, cols):
ways[col] += ways[col - 1]
return ways[-1]
For a three-by-three grid, completed rows are [1,1,1], [1,2,3], then [1,3,6]. The answer is six.
Reversing the sweep reuses stale left counts and returns four instead.
The reference uses additions and integer slots. Exact counts grow, so these are not fixed-bit costs.
One row or one column gives one route. Zero or negative dimensions are outside the reference contract.
Recall: Which value has already advanced in time? The left slot belongs to the current row; the current slot still belongs above.
Block Selected Cells
Choose this when: Some cells cannot be entered.
Accept a rectangular grid of obstacle flags; truthy entries are blocked. Start with one arrival at the origin, then process its flag too.
A blocked cell resets its count to zero. Otherwise, the same old-above/new-left addition applies.
def paths_with_obstacles(blocked):
if not blocked or not blocked[0]:
return 0
ways = [0] * len(blocked[0])
ways[0] = 1
for row in blocked:
for column, obstacle in enumerate(row):
if obstacle:
ways[column] = 0
elif column:
ways[column] += ways[column - 1]
return ways[-1]
A three-by-three grid with its center blocked has two routes. A blocked start or destination gives zero, including a single blocked cell.
Empty grids return zero. Input rows are not modified. The algorithm uses additions and integer slots.
Keep Only a Residue
Choose this when: The output requires the count modulo a positive integer, not the exact count.
Transposing an obstacle-free rectangle preserves the count. Allocate the shorter dimension, and reduce initialization as well as every addition.
def unique_paths_mod(rows, columns, modulus):
if modulus <= 0:
raise ValueError("positive modulus required")
if rows <= 0 or columns <= 0:
return 0
rows, columns = max(rows, columns), min(rows, columns)
ways = [1 % modulus] * columns
for _ in range(1, rows):
for column in range(1, columns):
ways[column] = (ways[column] + ways[column - 1]) % modulus
return ways[-1]
Six routes modulo five give one. Modulus one gives zero even for a one-cell grid.
A nonpositive modulus raises ValueError. Nonpositive dimensions return zero when the modulus is valid.
The algorithm uses modular additions and residue slots. Residue arithmetic still depends on modulus bit length.
Transfer
Unrestricted four-direction movement destroys this predecessor order. Revisiting can introduce cycles and infinitely many walks, so the same recurrence no longer specifies the task.