How do you count the number of unique paths through a grid where you may only move right or down?
Every path into a cell must arrive from the cell above it or the cell to its left, so the number of paths to a cell is the sum of the paths to those two cells. Fill the grid from the top left corner and read the answer from the bottom right.
def unique_paths(rows, cols):
table = [[1] * cols for _ in range(rows)]
for r in range(1, rows):
for c in range(1, cols):
table[r][c] = table[r - 1][c] + table[r][c - 1]
return table[rows - 1][cols - 1]
print(unique_paths(3, 7))
print(unique_paths(3, 2))The outputs are 28 and 3. A three by seven grid has twenty eight routes and a three by two grid has three.
The mechanism is the additive recurrence. The first row and the first column are seeded with one, because there is exactly one way to travel along the top edge or down the left edge. Every interior cell then accumulates the two contributions, and because the fill order respects the dependencies, every cell is correct by the time it is used.
The trade-off to name is that the table costs space quadratic in the product of the dimensions, when only the last row is really needed, since each row depends only on the row above it. The rolling array version uses linear space and is the one to reach for when the grid is large. The other point is the closed form: the answer is a binomial coefficient, and computing it directly is faster than filling a table, though the table version is what you should write in an interview because it is much easier to verify.