Dynamic programming and grid paths
Count routes, handle obstacles and derive a reusable recurrence instead of enumerating every path.
Core concepts and method
Dynamic programming stores answers to smaller subproblems. Define a state before writing a recurrence: for grid routes, W(r,c) is the number of ways to reach cell (r,c) from the start.
If only down and right moves are allowed, every arrival came from above or the left, so W(r,c) = W(r−1,c) + W(r,c−1). Start with W(0,0)=1; outside the grid and blocked cells contribute zero.
Fill the table row by row. For weighted routes replace addition by the relevant minimum or maximum, and include the cell cost exactly once. A four-way maze is different: the dependencies can cycle, so consider shortest-path algorithms.
Worked example
Count routes across a 3-by-3 grid of cells from (0,0) to (2,2), with (1,1) blocked.
- First row and column are all 1, because there is only one straight route to each.
- Middle row is 1, 0, 1. The blocked centre contributes zero, not one.
- Bottom row becomes 1, 1, 2. The destination has two routes, matching the two routes around the outside. Without the obstacle the count would be 6.
Try it yourself
A 4-by-3 grid of cells has no blocks. How many right/down routes reach (3,2) from (0,0)?
Show a hint
Each path consists of three down moves and two right moves.
Check your reasoning
Choose which two of the five moves are right: 5 × 4 / 2 = 10. The recurrence gives the same value.
Practice the technique
These competition questions use related mathematical ideas. You can check your answers as a guest; sign in to save your progress.
- Sparse-barrier monotone routes · easy · 25 min
- Right-and-down energy path · easy · 25 min
- Odd-value coin change · easy · 25 min
About the editorial approach · Report a mistake in this lesson