Count a robot's routes across a grid moving only right or down. Each cell's count is the cell above plus the cell to the left.
▼The problem
LeetCode 62 (Medium). A robot starts in the top-left corner of an m × n grid and can only move right or down. How many different paths reach the bottom-right corner?
Example (LeetCode's): m = 3, n = 7 → 28.
1 1 1 1 1 1 1 1 2 3 4 5 6 7 1 3 6 10 15 21 28TRY IT ON LEETCODE ▶
The solution
def uniquePaths(m, n):
row = [1] * n
for r in range(1, m):
for c in range(1, n):
row[c] += row[c - 1] # above + left
return row[-1]Transcript
Unique Paths. A delivery robot starts in the top left corner of a city grid. It can only move right or down. How many different paths lead to the bottom right corner?
Take a grid three rows tall and seven columns wide. Every path makes six moves right and two moves down; only the order changes. Here's one path, and here's another. Count them all, and you get twenty-eight.
The naive way tries every path. At each corner, go right, then go down, and count every arrival at the goal. But the paths branch at every step, so the work grows exponentially: a ten by ten grid has over forty-eight thousand paths. Worse, the same corners get walked again and again. The corner just left of the goal is walked twenty-one times.
Here's the key. Every path into a corner arrives from one of two places: the corner above, or the corner to the left. So the paths here are the paths above, plus the paths to the left. Four from above, six from the left: ten. And along the top row and the left column, there's only one way in: straight along the edge.
Let's fill the grid. The top row is all ones. Second row: one, then two, three, four, five, six, seven. Third row: one, then three, six, ten, fifteen, twenty-one. And the goal: seven from above, plus twenty-one from the left. Twenty-eight.
In code, we don't need the whole grid. Keep one row of counts, starting as all ones. For each new row, walk left to right. Each cell already holds the count from above, so just add the count on its left. After the last row, the last cell is the answer.
Every corner is filled once, so the time is order m times n. The space is one row: order n. And there's a shortcut. A path is just a choice of which two of the eight moves go down. Eight choose two is twenty-eight, again.
Above plus left, corner by corner. That's Unique Paths.