A robot starts on the top-left cell of a grid with m rows and n columns, at position (0, 0). It needs to reach the bottom-right cell at position (m - 1, n - 1). On each move the robot goes exactly one cell to the right or one cell down.
Return the total number of distinct paths the robot can take from the start to the finish.
Function Signature
def unique_paths(m: int, n: int) -> int:
Rules
-
m
is the number of rows and
n
is the number of columns.
-
Two paths are different when their sequences of moves differ.
-
When
m = 1
and
n = 1
, the robot already stands on the finish. The path with no moves counts as one path, so the answer is 1.
Constraints
-
1 <= m, n <= 125
-
The answer is at most
2 * 10^9
.
Examples
s . . . .
. . . . .
. . . . .
. . . . f
(s = start, f = finish)
Input: m = 4, n = 5
Output: 35
Every path makes exactly 3 down moves and 4 right moves, 7 moves in total. Choosing which 3 of the 7 moves go down gives C(7, 3) = 35 paths.
Input: m = 2, n = 4
Output: 4
Paths:
1. Right -> Right -> Right -> Down
2. Right -> Right -> Down -> Right
3. Right -> Down -> Right -> Right
4. Down -> Right -> Right -> Right
The single down move can come before the first right move, between two of them, or after the last one, which gives 4 positions.
Input: m = 1, n = 6
Output: 1
With one row the robot can only move right, so there is exactly one path.