The problem, in one line. A robot starts at the top-left of a grid and may only move right or down. Count the different routes to the bottom-right. LeetCode 62.
The tell. “Count the ways” with moves that only go forward. Whenever the last step into a cell can only come from a small, fixed set of cells, the ways to reach it are the sum of the ways to reach those.
The wrong first idea
Walk every route. At each cell try right, then try down, and count the times you land on the goal.
def paths(r, c):
if r == 0 or c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
It is correct, but it counts routes one at a time. An 18 by 18 grid has 2,333,606,220 routes, so the recursion makes billions of calls to build a number that a 324-cell table holds.
The invariant
This card is the one-page version of Clinic #21: Unique Paths. Fill the grid row by row. The cell you stand on can only have been entered from above or from the left, so its count is those two counts added.
flowchart LR A["above: 3"] --> C["this cell: 3 + 6 = 9"] B["left: 6"] --> C
The sentence that stays true every step: the count at a cell is the count above it plus the count to its left. The top row and left column are all 1, since there is only one way along an edge.
The solution
def unique_paths(m, n):
row = [1] * n # top row: one way to reach each cell
for _ in range(1, m):
for j in range(1, n):
row[j] += row[j - 1] # from above (old row[j]) plus from the left
return row[-1]
print(unique_paths(3, 7))
print(unique_paths(3, 2))
print(unique_paths(1, 1))
28
3
1
func uniquePaths(m, n int) int {
row := make([]int, n)
for j := range row {
row[j] = 1 // top row: one way to reach each cell
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
row[j] += row[j-1] // from above (old row[j]) plus from the left
}
}
return row[n-1]
}
Same three calls print 28, 3, 1.
Complexity
- Time O(m times n): every cell is visited once and costs one add.
- Space O(n): only one row is kept, because a cell needs only the row just above and the cell just left.
Traps
- Starting the edges at 0. Then every cell is 0 and the answer is 0. The first row and column must be 1.
- Looping
jfrom 0 in the one-row version. Cell 0 has no left neighbour, sorow[-1]wraps to the far end and corrupts it. - Using the number of moves as the grid size. A 3 by 7 grid needs 2 downs and 6 rights, so sizing the table by 3 and 7 moves is an off-by-one.
Next in the ladder
Longest Common Subsequence keeps the grid and the “look up, left” habit, but the two axes are now two strings, and a third neighbour on the diagonal joins in when the letters match.