1def count_paths(grid):2 R, C = len(grid), len(grid[0])3 ways = [[0] * C for _ in range(R)]4 for r in range(R):5 for c in range(C):6 if grid[r][c] == "#":7 continue8 if r == 0 and c == 0:9 ways[r][c] = 110 if r > 0:11 ways[r][c] += ways[r-1][c]12 if c > 0:13 ways[r][c] += ways[r][c-1]14 return ways[R-1][C-1]start0,10,20,31,01,11,21,32,02,12,2goal
Cells: routes from the start to that squareTokens: ways(above) and ways(left) carried into a squareRobot: one route walked move by moveThe Python function count_paths on the card; each cell of the 3 × 4 table holds the number of routes from the start to that square. A cell is the sum of the cell above it and the cell to its left, so filling row by row needs one addition per square: 10 routes, or 4 once a rock blocks square (1, 1).

The question

  1. A robot starts on the top-left square of a 3 by 4 grid and must reach the bottom-right square. Each move goes one square right or one square down. How many different routes can it take?

Fill the table

Rocks and cost

What happens

;; step 1/10 · routes
grid: 3 rows × 4 columns, squares (row, column)
start (0, 0), goal (2, 3)
moves: right (column + 1) or down (row + 1)

Each square needs the square above and the square to its left. Filling row by row, left to right, always has both ready. In MIT 6.006 terms that is a topological order of the subproblems: they form a DAG, so a plain loop can solve them bottom up. With no rocks, an R by C grid has C(R + C - 2, R - 1) routes: R + C - 2 moves, choose which R - 1 go down. Python 3.8 and later give it as math.comb; math.comb(30, 15) is 155,117,520. One rock breaks the formula, but not the table.