Sub topic 4
Filling the Table in the Right Order
This chapter assumes you can read nested Python loops, index a 2D list as dp[i][j], and follow a recurrence such as dp[i][j] = dp[i - 1][j] + dp[i][j - 1]. The previous chapters covered what a cell stores, how moves become recurrences, and how base cases protect the edges. This chapter covers the remaining question: in what order do you visit the cells so that every value a cell reads has already been computed?
Dependencies Form a Graph
A recurrence says which cells each cell reads. Draw an arrow from every cell to each cell that reads it, and you get a dependency graph. A valid fill order is any order in which every arrow points forward, so a cell comes after all the cells it reads. Graph theory calls this a topological order. It exists only when the graph has no cycles.
For a recurrence that reads the cell above and the cell to the left, the arrows on a 3×3 grid look like this:
Every arrow points right or down. Any order that never visits a cell before the cells above it and to its left is valid, and more than one order qualifies.
What a Wrong Order Looks Like
A wrong fill order rarely crashes. The table starts full of zeros, so reading a cell that has not been computed yet returns a plausible-looking 0, and the result comes out wrong without any error. The function below fills the same recurrence with whichever row and column ranges you pass in:
def fill(m, n, rows, cols):
dp = [[0] * n for _ in range(m)]
for i in rows:
for j in cols:
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
m, n = 3, 4
print(fill(m, n, range(m), range(n))) # 10 (correct)
print(fill(m, n, range(m - 1, -1, -1), range(n))) # 1 (silently wrong)With the rows reversed, row 2 is filled first and reads row 1 while row 1 still holds zeros. No exception is raised. You just get the wrong number.
Checking an Order Mechanically
You don't have to trust your intuition here. You can test an order directly: walk through it, and at each cell confirm that every dependency is already done. The script below checks four common orders against two recurrences.
def deps_up_left(i, j, m, n):
out = []
if i > 0:
out.append((i - 1, j))
if j > 0:
out.append((i, j - 1))
return out
def deps_falling(i, j, m, n):
# reads up-left, up, and up-right (a "falling path" recurrence)
if i == 0:
return []
return [(i - 1, j + dj) for dj in (-1, 0, 1) if 0 <= j + dj < n]
def row_major(m, n):
return [(i, j) for i in range(m) for j in range(n)]
def col_major(m, n):
return [(i, j) for j in range(n) for i in range(m)]
def anti_diagonal(m, n):
return [(i, d - i) for d in range(m + n - 1)
for i in range(m) if 0 <= d - i < n]
def reverse_row_major(m, n):
return row_major(m, n)[::-1]
def check_order(order, deps, m, n):
done = set()
for i, j in order:
for d in deps(i, j, m, n):
if d not in done:
return f"fail: {(i, j)} needs {d}"
done.add((i, j))
return "ok"
m, n = 3, 3
orders = [("row_major", row_major), ("col_major", col_major),
("anti_diagonal", anti_diagonal), ("reverse", reverse_row_major)]
for dname, deps in [("up/left", deps_up_left), ("falling", deps_falling)]:
for oname, order in orders:
print(dname, oname, check_order(order(m, n), deps, m, n))The output:
| Recurrence reads | row_major | col_major | anti_diagonal | reverse |
|---|---|---|---|---|
| up, left | ok | ok | ok | fail: (2, 2) needs (1, 2) |
| up-left, up, up-right | ok | fail: (1, 0) needs (0, 1) | ok | fail: (2, 2) needs (1, 1) |
Column-major order works for the up/left recurrence because the problem is symmetric. It fails for the falling recurrence because cell (1, 0) needs (0, 1), and column 1 hasn't been visited yet. Anti-diagonal order passes both: the up-right neighbor (i - 1, j + 1) lies on the same diagonal as (i, j), but it has a smaller row index, so the inner loop reaches it first.
A Rule for Nested Loops
Write each dependency as an offset (di, dj) from the current cell. Reading the cell above is (-1, 0), and reading the cell to the left is (0, -1). With rows in the outer loop and columns in the inner loop, a dependency is safe when one of these holds:
dipoints toward rows already finished. That meansdi < 0when rows ascend anddi > 0when rows descend. Anydjis fine in this case, because the whole earlier row is complete.di == 0anddjpoints toward columns already visited in the current row.
The table below applies the rule to common move sets.
| Cell reads | Offsets | Row loop | Column loop |
|---|---|---|---|
| up, left | (-1, 0), (0, -1) | ascending | ascending |
| up-left, up, up-right | (-1, -1), (-1, 0), (-1, 1) | ascending | either |
| down, right | (1, 0), (0, 1) | descending | descending |
| up, right | (-1, 0), (0, 1) | ascending | descending |
| left only | (0, -1) | either | ascending |
| left and right in the same row | (0, -1), (0, 1) | none works | none works |
The "down, right" row is the pattern behind problems solved backward from the goal, which a later chapter covers. The "falling" row shows that the column direction stops mattering once every dependency sits in an earlier row. Later in the tutorial, that freedom is what allows a single row to be updated in place.
When No Loop Order Works
The last row of the table has dependencies that point both ways inside one row. Cell (i, j) needs (i, j + 1), and (i, j + 1) needs (i, j). That is a cycle, so no topological order exists. You have three ways out:
- Reformulate the state. Many cycles go away if you add a direction or a step count to the state, so that each move goes from layer k to layer k + 1.
- Split into passes. Sometimes the answer for a row is the best of a left-to-right sweep and a right-to-left sweep, with each sweep depending in one direction only. This works only if the optimal route never needs to change direction more than the passes allow.
- Use a graph algorithm. If costs are non-negative and moves can go anywhere, the problem is a shortest-path problem. Dijkstra's algorithm handles it, and a fixed loop order does not.
Moves in all four directions do not always create a cycle. If a rule such as "only step to a strictly larger value" keeps the graph acyclic, a topological order exists, but it depends on the cell values, not on the coordinates. Nested loops can't express that order. Memoized recursion finds it automatically, and a later chapter on the longest increasing path uses this approach.
Common Errors
- Reversing one loop without reversing the recurrence. If you change
range(m)torange(m - 1, -1, -1)and keepdp[i - 1][j], every row reads uninitialized cells. The loop direction and the offsets must change together. - Swapping loop nesting. Moving the column loop to the outside is safe only when the offset rule still holds with columns as the outer index. The falling recurrence breaks under this change.
- Filling base cases after the main loop. If the first row and column are set in a separate loop that runs later, the interior has already read zeros. Either set the base cases first or handle them inside the main loop, as
filldoes. - Trusting a test on a square grid. A transposition bug, such as using
mwhere you meantn, can pass on a 3×3 grid and fail on a 3×4 grid. Test with non-square shapes.
Exercises
Exercise
A recurrence sets dp[i][j] from dp[i + 1][j] and dp[i][j - 1]. Which row and column loop directions fill it correctly with rows in the outer loop?
Show answer
Rows descending, from m - 1 down to 0, because the offset (1, 0) points to a later row that must already be finished. Columns ascending, from 0 to n - 1, because the offset (0, -1) points to an earlier column in the same row.
Exercise
The falling recurrence reads (i - 1, j - 1), (i - 1, j), and (i - 1, j + 1). Explain why the column loop direction doesn't matter, and why column-major order fails.
Show answer
Every dependency is in row i - 1, which row-major order completes before row i starts, so the column order inside a row doesn't matter. Column-major order visits (1, 0) before (0, 1), but (1, 0) reads (0, 1) through the up-right offset, so it reads an uncomputed value.
Exercise
Add a deps function to the checker for a recurrence that reads up and right, (i - 1, j) and (i, j + 1). Build an order with rows ascending and columns descending, and confirm that checkorder returns "ok" while rowmajor fails.
Show answer
deps returns (i - 1, j) when i > 0 and (i, j + 1) when j + 1 < n. The order is [(i, j) for i in range(m) for j in range(n - 1, -1, -1)], and it passes. Plain row_major fails at the first cell, "fail: (0, 0) needs (0, 1)", because (0, 1) hasn't been visited yet.