awelgorithms

Grid unique paths

Updated

dp[r][c] = paths to (r,c) from (0,0) with only right and down: dp[r][c] = dp[r-1][c] + dp[r][c-1]. First row and first col are 1 if unblocked. Encode m,n as a = [m, n].

What to focus on

A blocked cell is 0 and contributes nothing to neighbors. Do not DFS-count on an open grid; the table is O(mn).

Worked examples

2x3

a = [2, 3]
  1. row0: 1,1,1
  2. row1: 1,2,3

Result: 3 paths

1x3

a = [1, 3]
  1. only right moves
  2. dp = [1, 1, 1]

Result: 1

2x2

a = [2, 2]
  1. row0: 1,1
  2. row1: 1,2

Result: 2 paths

Try it

Write uniquePaths(m, n). m and n are grid sizes encoded as a = [m, n]. dp[r][c] is paths to (r, c) from (0, 0) with only right and down. Fill the table. Return the bottom-right cell. a = [2, 3] → 3. [1, 3] → 1. [2, 2] → 2.

The grid is open (no walls). m and n are integers ≥ 1. Moves are only right and down. A path from (0,0) to (m-1,n-1) exists.