Sub topic 4
Filling the Table in the Right Order
This chapter assumes you can read nested Python loops, index a 2D list by row and column, and follow a recurrence like dp[i][j] = dp[i-1][j] + dp[i][j-1]. The earlier chapters covered how to define the state and choose base cases. This one covers the order in which you compute the cells.
The Rule: Dependencies First
A recurrence reads some cells to compute another. If the code reads a cell before anything has written to it, the result comes from an initial placeholder such as 0 or inf. Python raises no error in that case. You just get a wrong answer. A fill order is valid when every cell a recurrence reads has already been computed.
To pick a valid order, follow these steps:
- Write down the offsets your recurrence reads, such as
(-1, 0)for "the cell above". - Draw an arrow from each dependency to the cell that needs it.
- Choose a loop order that visits cells in the direction of those arrows.
The arrows all point down or to the right. A row-major loop (top to bottom, then left to right inside each row) follows those arrows. A column-major loop does too.
Checking an Order Mechanically
You can test any order against a set of dependency offsets. The checker below simulates the fill and reports whether any read happens too early.
def check_order(m, n, order, deps):
cells = {(i, j) for i in range(m) for j in range(n)}
done = set()
for i, j in order:
for di, dj in deps:
p = (i + di, j + dj)
if p in cells and p not in done:
return False
done.add((i, j))
return True
m, n = 3, 4
row_major = [(i, j) for i in range(m) for j in range(n)]
col_major = [(i, j) for j in range(n) for i in range(m)]
backward = [(i, j) for i in reversed(range(m)) for j in reversed(range(n))]
row_right_to_left = [(i, j) for i in range(m) for j in reversed(range(n))]
up_left = [(-1, 0), (0, -1)]
up_left_diag = [(-1, 0), (0, -1), (-1, -1)]
down_right = [(1, 0), (0, 1)]
up_and_right = [(-1, 0), (0, 1)]
print(check_order(m, n, row_major, up_left)) # True
print(check_order(m, n, col_major, up_left)) # True
print(check_order(m, n, row_major, up_left_diag)) # True
print(check_order(m, n, backward, up_left)) # False
print(check_order(m, n, backward, down_right)) # True
print(check_order(m, n, row_major, up_and_right)) # False
print(check_order(m, n, row_right_to_left, up_and_right)) # TrueCells that fall outside the grid are skipped here, because the boundary handling from the previous chapter covers them.
Matching Dependencies to Loops
| Recurrence reads | Valid fill order |
|---|---|
| above, left | rows top to bottom, columns left to right |
| above, left, upper-left diagonal | same as above |
| below, right | rows bottom to top, columns right to left |
| above, right | rows top to bottom, columns right to left |
| any of 4 neighbors, with no fixed direction | no loop order works, so use memoized DFS |
The row loop's direction depends on the vertical offsets. The column loop's direction depends on the horizontal offset within the same row. Reads from the row above put no constraint on the column direction, because that whole row is already done.
When No Loop Order Exists
Suppose moves can go in all four directions. Then the arrows can form a cycle, and no ordering of rows and columns works. A problem becomes solvable only if some rule, such as "values must strictly increase", removes the cycles. The dependency graph is then a DAG (a directed graph with no cycles). Recursion with memoization visits cells in a valid order without you having to spell it out. A later chapter covers this case.
Exercise
A recurrence is dp[i][j] = grid[i][j] + min(dp[i+1][j], dp[i][j-1]). Which row direction and column direction make a valid fill order?
Show answer
Rows go bottom to top, because the recurrence reads the row below (i+1). Columns go left to right, because within a row it reads the left neighbor (j-1). In Python: for i in reversed(range(m)): for j in range(n).
Exercise
Why does reading dp[i-1][j+1] (upper-right) still work with a plain row-major loop?
Show answer
Row i-1 is completely filled before row i starts, so every cell in it, including column j+1, is already computed. The column direction only matters for reads within the same row.