Grid paths and counting
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A robot crosses a grid, moving only right or down. How many routes are there? Listing them is hopeless on big grids: a 16 by 16 grid has 155,117,520. Instead, fill a table where each square holds the routes that reach it, the sum of the square above and the square to its left. Watch the 3 by 4 table fill to 10, then refill to 4 around a rock. The Software lesson "Dynamic programming" covers memoisation and tables, and "Defining states and transitions" covers how to name a state.
How many routes?
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?
grid: 3 rows × 4 columns, squares (row, column) start (0, 0), goal (2, 3) moves: right (column + 1) or down (row + 1)
اقرأ الدرس خطوة بخطوة
How many routes?
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?
grid: 3 rows × 4 columns, squares (row, column) start (0, 0), goal (2, 3) moves: right (column + 1) or down (row + 1)Listing every route
Every route is 5 moves: 3 right and 2 down, in some order. Listing them works for this small grid, but the list explodes: a 16 by 16 grid has 155,117,520 routes. We need to count without listing.
route 1: R R R D D route 2: D D R R R every route: 3 × R and 2 × D 16 × 16 grid: 15 R + 15 D = 30 moves, 155,117,520 routesLook at the last move
Any route into a square arrives from the square above it or from the square to its left. So ways(r, c) = ways(above) + ways(left). That is the state and the transition: each count needs only two smaller counts.
state: ways(r, c) = routes from the start to (r, c) transition: ways(r, c) = ways(r-1, c) + ways(r, c-1) example: ways(1, 2) = ways(0, 2) + ways(1, 1) code lines 11 and 13The start and the edges
The start holds 1: the route that has not moved yet. A top-row square can only be reached from the left, and a left-column square only from above, so each of them holds 1 too.
base case: ways(0, 0) = 1 (line 9) top row: ways(0, c) = ways(0, c-1) = 1 left col: ways(r, 0) = ways(r-1, 0) = 1 off the grid counts as 0Fill row 1
Go left to right. (1, 1) = 1 above + 1 left = 2. Then (1, 2) = 1 + 2 = 3, and (1, 3) = 1 + 3 = 4. Both numbers a square needs are always filled already.
ways(1, 1) = 1 + 1 = 2 ways(1, 2) = 1 + 2 = 3 ways(1, 3) = 1 + 3 = 4 row by row, left to right: a topological orderFill row 2
Same again: 2 + 1 = 3, then 3 + 3 = 6, then 4 + 6 = 10. The goal holds 10: there are 10 routes. We did one small sum per square, not one walk per route.
ways(2, 1) = 2 + 1 = 3 ways(2, 2) = 3 + 3 = 6 ways(2, 3) = 4 + 6 = 10 answer: ways(2, 3) = 10Check: 5 choose 2
Check another way. A route is 5 moves, and picking which 2 of them go down fixes the route: 5 choose 2 = 10. But the formula needs an empty grid.
route R D R R D: down at moves 2 and 5 C(5, 2) = 5 × 4 / 2 = 10 empty R × C grid: C(R + C - 2, R - 1) Python: math.comb(5, 2) == 10Drop a rock
Now a rock blocks square (1, 1). No route may pass through it, so it holds 0. The formula no longer fits, but the table still works: line 6 skips the rock and leaves its count at 0.
grid = ["....", ".#..", "...."] ways(1, 1) = 0 (line 6: continue) the other squares must be filled againRefill around the rock
Same order, same sums. Row 1: 1 + 0 = 1, 1 + 1 = 2. Row 2: 0 + 1 = 1, 1 + 1 = 2, and the goal 2 + 2 = 4. Only 4 of the 10 routes dodge the rock.
ways(1, 2) = 1 + 0 = 1 ways(1, 3) = 1 + 1 = 2 ways(2, 1) = 0 + 1 = 1 ways(2, 2) = 1 + 1 = 2 ways(2, 3) = 2 + 2 = 4 count_paths(grid) returns 4Rows times columns
The loops visit each square once and do at most two additions there, so an R by C grid costs O(R × C) time. A 16 by 16 grid is 256 squares, against 155,117,520 routes to list.
subproblems: R × C squares work per square: O(1), at most 2 additions time: O(R × C), memory: O(R × C) for the table 16 × 16: 256 squares vs 155,117,520 routes keep one row only: memory O(C)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01On an empty grid, 4 routes reach the square above the goal and 6 reach the square to its left. How many routes reach the goal?
Every route arrives through exactly one of the two neighbours, so the counts add: 4 + 6 = 10, the goal in the figure. Multiplying (24) would count pairs of routes, not routes.
02Why does the code fill the table row by row, left to right?
The subproblems form a DAG: each square depends only on squares above or to its left. Row by row, left to right is a topological order of that DAG, so both inputs are always ready.
03A rock blocks a square. What value does that square get in the table?
No route may pass through the rock, so 0 routes reach it. A 0 adds nothing to the squares after it, which is how the table routes around the rock.
04How many routes cross an empty 3 by 3 grid of squares from top-left to bottom-right?
Each route is 4 moves, 2 right and 2 down. Choosing which 2 of the 4 go down gives C(4, 2) = 6. The table gives the same: the last row reads 1, 3, 6.
05What does count_paths cost on an R by C grid?
The two loops visit each of the R × C squares once and do at most two additions there. Listing routes one by one would cost at least as much as the number of routes, which grows exponentially.
المسرد
- Grid path
- A route from the start square to the goal square that moves only right or down, one square at a time.
- State
- The small question one table entry answers. Here: ways(r, c), the number of routes from the start to square (r, c).
- Transition
- The rule that builds a state from smaller ones. Here: ways(r, c) = ways(r - 1, c) + ways(r, c - 1).
- Base case
- A state answered without the rule. Here the start holds 1, and squares off the grid or under a rock count as 0.
- DAG (directed acyclic graph)
- A set of tasks joined by one-way arrows with no loops, so you can never come back to where you started. Here each square points to the squares that need it.
- Topological order
- An order of the subproblems where each one comes after every subproblem it needs. Row by row, left to right is one for this grid.
- Bottom-up (tabulation)
- Solving every subproblem in a loop, smallest first, and storing the answers in a table.
- Binomial coefficient C(n, k)
- The number of ways to choose k items from n. An empty R by C grid has C(R + C - 2, R - 1) routes.
الملاحظات والمصادر
- 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.
- The table holds R × C numbers, but each row only reads the row above it. Keeping one list of C numbers and updating it in place (ways[c] += ways[c-1]) gives the same answer with O(C) memory.
- Build the table with [[0] * C for _ in range(R)]. Writing [[0] * C] * R makes R references to one shared list, so a change to one row shows up in every row (Python FAQ). Python integers never overflow, so huge counts stay exact.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 15: Dynamic Programming, Part 1 (SRTBOT)
- MIT 6.006 Lecture 15 notes (PDF): topological order on subproblems, bottom-up via loops
- Sedgewick and Wayne, Algorithms 4th ed., §4.4 Shortest Paths (relaxing a DAG in topological order)
- Sedgewick and Wayne, Computer Science, §2.3 Recursion (dynamic programming, binomial coefficients)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), Chapter 14: Dynamic Programming
- Python FAQ: How do I create a multidimensional list?
- Python docs: math.comb
اختبار يتاح بعد الخطوة الأخيرة.