progress

~/problems / 2-D dynamic programming / Grid DP

Unique Paths

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

medium ▶ boss game: The Castle Road 2 levels ~20 min

Level 1 Unique Paths

A knight waits in the top-left square of an m x n board, and the castle stands in the bottom-right. Every move goes one square right or one square down.

Write unique_paths(m: int, n: int) -> int: how many different routes reach the castle. m is the number of rows, n the number of columns.

unique_paths(7, 7)   # 924
unique_paths(3, 2)   # 3    right-down-down, down-right-down, down-down-right
unique_paths(2, 3)   # 3
unique_paths(1, 5)   # 1    one row: only right, right, right, right
unique_paths(1, 1)   # 1    the knight is already at the castle

1 <= m, n <= 100. The answer can be huge (59 digits for 100 x 100); return the exact count. Walking every route one by one is hopeless (a 16 x 16 board has over 155 million).

⭐ Bonus: a speed test with board shapes up to 100 x 100 earns a star in O(m·n).

Show hint

the last move into a square came from above or from the left. How do those two counts give this one?

Level 2 unlocks when level 1 passes.

Topic: Grid DP. dp[r][c] from neighbours; add a dimension for extra state (jumps left).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc