Recursion and dynamic programming: count states, not repeated paths
递归与动态规划基础
Derive a grid-path recurrence, compare recursion with memoization and tabulation, and prove the rolling-row invariant.
recursion-dynamic-programmingThe same junction should not require the same calculation twice
A marker moves from the top-left to the bottom-right of a rectangular grid. It may move one cell down or one cell right, and it cannot enter blocked cells. How many legal routes exist?
A recursive answer is natural: count the routes after moving down, count those after moving right, then add them. But two different prefixes can reach the same cell. From there, the remaining problem is identical, so recomputing its answer wastes work.
Dynamic programming makes that repeated problem explicit and reuses its solution. It is not merely “put a cache on any recursive function.” We need a state that determines the answer, a relation between states, base cases and an evaluation order. The MIT recursive-algorithms notes organize recursive design around these obligations and compare top-down memoization with bottom-up evaluation.
We will solve one obstacle grid four ways: direct recursion, memoized recursion, a full table and a rolling row. They agree on the route count but perform different amounts of work and retain different information.
Define exactly what a state means
Remaining routes and a decreasing measure
Let the grid have R rows and C columns, numbered from zero. Let G be its cells, O the blocked cells and t the bottom-right target. Define F(r,c) as the number of legal suffix routes from that cell to t, including a zero-move route when already at an unblocked target:
The blocked case takes precedence over the target case. Otherwise every route begins with exactly one of the two allowed moves. These two sets of routes are disjoint, and removing the first move gives a suffix route counted by the corresponding term. This proves the relation; induction proves the result once the smaller states are correct.
The problem really gets smaller because every in-grid move from (r,c) to (r',c') reduces the remaining Manhattan steps by one:
Thus dependencies have no cycle. A recursive call stack can follow a chain of at most R+C−1 in-grid cells. The number of calls can still be much larger than the depth: distinct prefixes may create many copies of the same suffix computation.
Memoization turns repeated calls into shared states
For a fixed grid and obstacle set, (r,c) is a sufficient cache key. A cache miss computes F once; a hit reuses it. A blocked cell’s zero is also a valid cached answer. The program creates a fresh cached function for each problem and captures an immutable obstacle snapshot. Reusing a global (r,c) cache while silently changing obstacles would return answers to the wrong problem.
Python’s functools.cache stores results by hashable arguments without an eviction limit. It does not establish that the arguments capture every relevant dependency. It also does not repair an incorrect base case, remove recursion depth, or turn a cyclic recurrence into an acyclic one.
A table can count prefixes instead
For the iterative version, let P(r,c) count legal routes from the start to a cell. Set a blocked cell to zero, set an unblocked start to one, and use zero for an out-of-grid predecessor. Every other free cell receives:
This is a different subproblem meaning from F, even though P(target)=F(start). Scanning rows from top to bottom and columns from left to right evaluates both predecessors first. The full table answers prefix-count questions for every cell, including unreachable ones whose count is zero. Top-down recursion only attempts cells reachable through an unblocked prefix, together with blocked cells where such a prefix first stops.
For a rolling row, before processing (r,c), ways[c] still holds the count from the preceding row; ways[c-1] already holds the count for the current row. Adding them performs the same recurrence. A blocked cell resets ways[c] to zero. Reversing the column order would use the wrong version of the left neighbor. Storage reduction depends on this invariant, not on the visual resemblance of two loops.
Four implementations, visible work counts
The complete Python 3.12 program accepts dimensions from 1 to 30 and a finite iterable of blocked coordinates. It rejects booleans, invalid shapes and out-of-grid cells. Duplicate obstacle records denote the same blocked cell and are collapsed after validation. Direct recursion additionally requires rows + columns <= 18, limiting this intentionally wasteful demonstration. The other implementations support the full stated dimension range.
The recursive report counts actual function-body calls. The memoized report distinguishes computed states (cache_info().misses) from cache hits; their sum is the number of calls to the wrapper. The table and rolling reports count every visited table cell, so updates=rows*columns even when the start is blocked. These counters measure different operations, not comparable wall-clock durations. The cache is cleared before returning its report.
from functools import cache
def prepare(rows, columns, blocked):
if type(rows) is not int or type(columns) is not int or not 1 <= rows <= 30 or not 1 <= columns <= 30:
raise ValueError('rows and columns must be integers from 1 to 30')
try:
cells = tuple(blocked)
except TypeError as exc:
raise ValueError('blocked must be a finite iterable of cells') from exc
obstacles = set()
for cell in cells:
if type(cell) not in (tuple, list) or len(cell) != 2:
raise ValueError('each blocked cell needs a row and column')
r, c = cell
if type(r) is not int or type(c) is not int or not 0 <= r < rows or not 0 <= c < columns:
raise ValueError('blocked cell is outside the grid or has invalid indices')
obstacles.add((r, c))
return rows, columns, frozenset(obstacles)
def count_recursive(rows, columns, blocked=()):
rows, columns, obstacles = prepare(rows, columns, blocked)
if rows + columns > 18:
raise ValueError('uncached teaching run requires rows + columns <= 18')
calls = 0
def visit(r, c):
nonlocal calls
calls += 1
if (r, c) in obstacles:
return 0
if (r, c) == (rows-1, columns-1):
return 1
down = visit(r+1, c) if r+1 < rows else 0
right = visit(r, c+1) if c+1 < columns else 0
return down + right
return {'count': visit(0, 0), 'calls': calls}
def count_memoized(rows, columns, blocked=()):
rows, columns, obstacles = prepare(rows, columns, blocked)
@cache
def visit(r, c):
if (r, c) in obstacles:
return 0
if (r, c) == (rows-1, columns-1):
return 1
down = visit(r+1, c) if r+1 < rows else 0
right = visit(r, c+1) if c+1 < columns else 0
return down + right
answer = visit(0, 0)
info = visit.cache_info()
result = {'count': answer, 'states': info.misses, 'hits': info.hits}
visit.cache_clear()
return result
def count_table(rows, columns, blocked=()):
rows, columns, obstacles = prepare(rows, columns, blocked)
table = [[0]*columns for _ in range(rows)]
for r in range(rows):
for c in range(columns):
if (r, c) in obstacles:
table[r][c] = 0
elif (r, c) == (0, 0):
table[r][c] = 1
else:
table[r][c] = (table[r-1][c] if r else 0) + (table[r][c-1] if c else 0)
return {'count': table[-1][-1], 'updates': rows*columns,
'table': tuple(map(tuple, table))}
def count_rolling(rows, columns, blocked=()):
rows, columns, obstacles = prepare(rows, columns, blocked)
ways = [0]*columns
ways[0] = 1
for r in range(rows):
for c in range(columns):
if (r, c) in obstacles:
ways[c] = 0
elif c > 0:
ways[c] += ways[c-1]
return {'count': ways[-1], 'updates': rows*columns}
def main():
blocked = ((1, 2), (3, 3))
print('recursive:', count_recursive(5, 6, blocked))
print('memoized:', count_memoized(5, 6, blocked))
table = count_table(5, 6, blocked)
print('table:', table['count'], table['updates'])
print('rolling:', count_rolling(5, 6, blocked))
print('single open / blocked:', count_rolling(1, 1)['count'],
count_rolling(1, 1, ((0, 0),))['count'])
print('fresh problem:', count_memoized(5, 6)['count'])
print('large table:', count_rolling(30, 30)['count'])
if __name__ == '__main__':
main()
Output:
recursive: {'count': 33, 'calls': 169}
memoized: {'count': 33, 'states': 30, 'hits': 16}
table: 33 30
rolling: {'count': 33, 'updates': 30}
single open / blocked: 1 0
fresh problem: 126
large table: 30067266499541040
On the 5-by-6 grid, direct recursion executes 169 bodies. Memoization computes 30 states and serves 16 hits, for 46 wrapper calls. Both table versions visit 30 cells. All return 33 routes. The fresh obstacle-free call returns 126, showing why cached answers must belong to a specific problem.
The full table is useful for inspecting where routes become impossible. The rolling version keeps only the count needed for the next update and cannot later answer every cell query. None of these functions returns an actual route; counting all routes and reconstructing a witness are separate output requirements.
What improved, and what still costs work?
Let Q be the number of supplied obstacle records, including duplicates, and let K be the number of distinct obstacles. Preparing an immutable validated set takes expected O(1+Q) work under standard hashing assumptions and O(1+Q) temporary slots. This cost exists even when the search stops immediately at a blocked start.
With P actual direct-recursion calls, its work is O(Q+P) integer operations and membership checks, with O(Q+R+C) peak auxiliary slots. For balanced large grids without obstacles, P is exponential in the side length. A simple upper bound is O(2^(R+C)), because there are at most two children per call. Thin grids need not exhibit that worst case.
Memoization uses expected O(Q+R*C) such operations and O(Q+R*C) auxiliary slots, including cached values and recursion frames. The full table uses O(Q+R*C) operations and slots. Rolling storage uses O(Q+C) peak auxiliary slots with the same O(Q+R*C) operation bound; after preparation it retains only K obstacle entries and C counts. These bounds count integer arithmetic as an operation. Exact counts can grow large: no-obstacle counts satisfy
Choose which of the R+C−2 moves are downward to prove the formula. The count needs at most O(R+C) bits, so ordinary addition is not universally constant time. A conservative bound for the table’s counting arithmetic is O(R*C*(R+C)) bit work, in addition to input handling. MIT notes, reusable subproblems and integer-size caveat
A smaller cache key can change the problem
Suppose the rules now forbid two downward moves in a row. Two prefixes reaching the same (r,c) may allow different next moves, depending on their last move. The state must include that last-move information. Caching only by cell would merge different subproblems. Similar omissions arise when the answer depends on remaining resources, a partial assignment or the version of input data.
Allowing left and upward moves changes another assumption. The decreasing measure no longer works; there may be cycles and infinitely many walks if revisits are allowed. Counting simple paths would require remembering visited cells, leading to a much larger state space. A memoization decorator does not decide which problem was intended.
Recursion is also an execution choice. Python has a recursion limit, and changing that limit is not a proof that enough stack memory exists. The small bounds here work in an ordinary interpreter configuration; a caller with an unusually small recursion limit can still encounter RecursionError. The iterative versions avoid the recursive call chain.
Dynamic programming does not always save much. If few subproblems repeat, a cache adds bookkeeping with little reuse. If the state space is exponential, solving every state once may still be infeasible. Before optimizing storage or adding a cache, write down what the state means and which smaller answers determine it.
Check state, order and reuse
- Check the empty route. A 1-by-1 grid has no blocked cell. Why is its answer one rather than zero? What if that only cell is blocked?
Apply the base cases in order
Answer: The marker already occupies the target, so there is exactly one zero-move route. If the cell is blocked, the obstacle case applies first and the answer is zero. Adding a move requirement would define a different counting problem.
- Derive the main answer without the recurrence. On the 5-by-6 grid, obstacles are
(1,2)and(3,3). Use inclusion–exclusion.
Count routes through each obstacle
Answer: There are choose(9,4)=126 unrestricted routes. Routes through the first obstacle number choose(3,1)*choose(6,3)=60; through the second, choose(6,3)*choose(3,1)=60. Those through both number choose(3,1)*choose(3,2)*choose(3,1)=27. Subtracting the two forbidden sets and restoring their intersection gives 126-60-60+27=33.
- Reverse the rolling scan. Starting from
[1,0,0], process a 2-by-3 empty grid with the updateways[c] += ways[c-1]but scan columns from right to left. What fails?
Identify which row each value belongs to
Answer: The final rightmost value becomes one instead of three. A right-to-left scan reads the left count from the previous row rather than the already-updated current row. Reversing a loop is not a valid memory optimization unless its dependency invariant changes too.
- Add a movement restriction. If two downward moves in a row are forbidden, is
(r,c)still a sufficient state?
Compare histories that meet at a cell
Answer: No. Prefixes ending in a downward move cannot move down next, whereas prefixes ending in a rightward move may do so. Include the last-move category, with a separate initial category or equivalent convention. Then derive new transitions and base cases; the original cached counts cannot be reused unchanged.
The dependency graph is the useful abstraction
The MIT notes connect recursive design, shared subproblem graphs and dynamic programming. Top-down and bottom-up methods are different schedules for evaluating dependencies; the subproblem definition and its proof remain the main design work. A counting example uses addition, while an optimization problem may combine predecessor values by minimum or maximum under its own assumptions.
The functools documentation describes the concrete cache mechanism, including hashable keys, retained values and cache inspection. Those implementation details support the recurrence; they cannot supply its semantics. Continue with data structures for the cost of memo tables, and algorithms and complexity for distinguishing operation counts, input size and integer bit cost.
Make a prediction, then check
If two downward moves in a row become forbidden, can the original cell-only cache be reused?
Learning objectives
- Define a sufficient state and prove an acyclic recurrence with the correct base cases.
- Compare actual recursive calls, memoized states and table-cell updates without confusing them with timings.
- Prove the rolling-row dependency invariant and account for cache scope and integer growth.
Prerequisites & connections
Explore related knowledge →References
- 6.006 Introduction to Algorithms, Lecture 15: Recursive Algorithms
MIT OpenCourseWare · 2020 - functools — Higher-order functions and operations on callable objects — Python 3.12
Python Software Foundation
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Seven tests pass on actual CPython 3.12.12. Independent move-position combinations compute every prefix-table cell; independent binary-prefix enumeration checks recursive calls and attempted-state sets, with graph-edge counts giving cache hits. All four complete reports agree across all 64 two-by-three obstacle sets and 24 additional small grids.
- Inclusion–exclusion independently gives the main answer 33; binomial formulas check five unblocked sizes including 30 by 30. Checked open/blocked singleton, full barriers, blocked target/start, duplicate obstacles, fresh-cache isolation and input snapshots, invalid trailing records, uncached-size guard and a wrong rolling-order counterexample. Seven actual stdout lines match both articles.
- Full original bilingual prose, identical Python, four matching displayed formulas, six anchors and four answered exercises pass strict MDX/KaTeX and actual React HTML/MathML. Only article_text sets test paths. Humanizer conventions followed; written records AI author checking rather than human review. No general cyclic-DP claim, recursion-limit change, timing benchmark or whole-site build.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- 6.006 Introduction to Algorithms, Lecture 15: Recursive Algorithms · Actually followed the official 2020 lecture-notes index to Lecture 15 and read its eight-page PDF: page 1 state/relation/order/base/original/time framework; pages 2–3 repeated recursive work, memoization, tabulation and integer bit-size caveat; page 4 shared-state DAG and time-by-state analysis; page 5 DAG shortest-path relation. Do not transfer the lecture’s informal claims about all recursive computations to arbitrary cyclic stateful functions. No Fibonacci or bowling code copied.
- functools — Higher-order functions and operations on callable objects — Python 3.12 · Actually read cache lines 11–31 and lru_cache lines 71–104: dictionary-backed unbounded cache, hashable arguments, cache_info/clear, retained references and side-effect limitations. State sufficiency and per-problem immutable closure are established by our grid model, not by the decorator. No concurrency guarantee beyond a single-threaded teaching run.
- 6.006 Introduction to Algorithms, Lecture 15: Recursive Algorithms · Actually opened and read the eight-page official PDF: printed page 1 state/relation/topological-order/base-case framework; pages 2–3 repeated recursive calls, memoization/tabulation and arithmetic bit growth; page 4 shared dependency graph and work-by-state analysis; page 5 DAG path relation. The article confines acyclicity to its decreasing-measure grid rather than overgeneralizing the lecture language. No visual scan review claimed.
- functools — Higher-order functions and operations on callable objects — Python 3.12 · Actually read the official versioned reference, displayed 3.12.13: cache lines 11–31 and lru_cache lines 71–104, including unbounded dictionary lookup, hashable arguments, cache_info/cache_clear, retained references and concurrent duplicate computation caveat. The implementation makes fresh per-problem closures and runs sequentially.
Related topics