Visualize

Pattern visualizer

Unique Paths

Every path to a cell arrives either from directly above or directly to the left — there's no other way in, since only right/down moves are allowed. So the number of ways to reach any cell is just the sum of the ways to reach those two neighbors, and the top row / left column are trivially 1 (a single straight line gets there). Filling the grid this way builds every answer from ones already computed. Animated on: 3x3 grid, top-left to bottom-right, moving only right or down — count the distinct paths..

dp[cell] = dp[above] + dp[left]

time O(m*n)space O(m*n)step 1 / 11
0
[0]
0
[1]
0
[2]
0
[3]
0
[4]
0
[5]
0
[6]
0
[7]
0
[8]
line 2

3x3 grid, flattened row-major. Only right/down moves are allowed, so the number of ways to reach a cell is just the sum of ways to reach the cell above and the cell to its left.

Pseudocode
1FUNCTION uniquePaths(m, n):
2 dp = an m by n grid
3 FOR each cell (i, j) in the grid:
4 IF i is 0 or j is 0: dp[i][j] = 1 (top row / left column)
5 ELSE: dp[i][j] = dp[i-1][j] + dp[i][j-1] (from above + from left)
6 RETURN dp[m-1][n-1]

← / → step · space play · Home restart

Where to practice Dynamic Programming