DP on Grids & the Zone Crossing
In short: on a grid where the van only moves right or down, every zone's
answer depends only on the zone above it and the zone to its left, and both
are already finished by the time you get there. So the grid doubles as the
table: no separate structure, no recursion, just a fill order where "above"
and "left" come first. Swap + for min and the same shape counts routes or
finds the cheapest one; closed zones become 0 routes or infinite cost so the
combine step quietly ignores them.
![A 3x3 cost grid for [[1,3,1],[1,5,1],[4,2,1]], each cell showing its running cost with arrows from above and left into the bottom-right corner 7, and the winning RRDD path traced in green](/api/assets/dsa/assets/fdab48196afb6ce5.png)
Meridian divides the city into a grid of service zones. Each zone has a congestion toll, and on any given morning a few are closed for roadworks. A van leaving the north-west depot for the south-east one works its way across the grid, and dispatch wants two numbers: how many routes are there, and which one is cheapest?
A grid needs no separate table. If the van only ever moves right or down, every zone can be reached only from the zone above it or the zone to its left, and those two zones already have their answers when you get there. The map is the table, and the only question left is the order you fill it in.
Counting routes
Every route into a zone arrives from above or from the left, and no route does both. So the counts simply add:
ways[r][c] = ways[r - 1][c] + ways[r][c - 1]
A closed zone has zero routes into it, and every count downstream quietly loses the routes that would have used it. Watch a 4 × 5 district fill with two zones closed (X):
Every cell on one anti-diagonal (r + c constant) depends only on the diagonal before it, so the answers sweep across the grid as a wavefront from the start corner.
The start has one route, the empty one. The two closed zones will stay at zero routes. 4 by 5 table. At row 0, column 0 — value 1. 3 of 20 cells filled.
The wavefront shows why the fill order is safe: a cell only ever reads cells on the diagonal before it. Row by row is one order that respects this, and column by column is another:
R, C = 3, 3
ways = [[1] * C for _ in range(R)]
for c in range(1, C): # columns outside,
for r in range(1, R): # rows inside
ways[r][c] = ways[r - 1][c] + ways[r][c - 1]
print(ways[R - 1][C - 1])The counts grow fast. Guess before you run it:
ways = [[1] * 10 for _ in range(10)]
for r in range(1, 10):
for c in range(1, 10):
ways[r][c] = ways[r - 1][c] + ways[r][c - 1]
print(ways[9][9])You only ever read the row above, so one row is enough. Step through the rolling
version, where each row[c] already holds "above" and gains "left":