Sub topic 16
Two Walkers at Once: Cherry Pickup
Earlier chapters covered minimum-cost paths and complexity analysis. You should be comfortable writing a right/down recurrence and counting the states in a DP table. This chapter works on one problem whose state has to describe two walkers at once instead of one cell.
The Problem
You get an n x n grid. Each cell holds one of three values:
0: an empty cell you can walk through1: a cherry, which you pick up and which leaves the cell empty-1: a thorn, which blocks the cell
Start at (0, 0) and walk to (n-1, n-1) moving only right or down. Then walk back to (0, 0) moving only left or up. Return the largest number of cherries you can collect. If no valid path exists, return 0.
Why the Greedy Answer Is Wrong
The obvious plan is to find the best forward path with min-path-sum style DP, remove its cherries, and then find the best return path on what remains. Each half is optimal, but the combined answer can still be worse than the best possible.
Here is a 7 x 7 grid with 15 cherries:
grid = [
[1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1],
]The best singles along the top row to column 3, down column 3, then along the bottom row. It collects 13 cherries. The cherries left over are at (3, 0) and (2, 6). One monotone path cannot reach both, because (2, 6) is above and to the right of (3, 0). So the greedy total is 14.
Two paths planned together collect all 15:
- Path A goes along row 0 to column 3, down to row 2, right to column 6, then down. It collects 8 cherries.
- Path B goes down column 0 to row 3, right to column 3, down to row 6, then right. It collects 7 new cherries.
Reframing: Two Forward Walkers
A return path that moves left/up, read in reverse, is an ordinary right/down path from (0, 0) to (n-1, n-1). So the round trip is the same as two walkers starting at (0, 0) together and walking to the goal together, with cherries on shared cells counted once.
Make the walkers move in lockstep. After t steps, every cell either walker can occupy satisfies r + c = t. This rule is what makes the problem tractable:
- Cell
(r, c)can only be visited at stept = r + c. - So if the two walkers ever share a cell, they share it at the same step.
- At a fixed step
t, walker 1 is at(r1, t - r1)and walker 2 is at(r2, t - r2). They are on the same cell exactly whenr1 == r2.
Without the shared step, you would need to remember which cells were already emptied, and that takes exponential state. With it, a collision check is a single comparison.
Defining the State
Let dp[t][r1][r2] be the maximum number of cherries collected when walker 1 is at (r1, t - r1) and walker 2 is at (r2, t - r2), both after exactly t steps. States where either walker stands on a thorn or outside the grid hold negative infinity, which means "unreachable."
A naive state (r1, c1, r2, c2) has n^4 entries. Each column is determined by t and its row, so the state shrinks to about 2n * n * n.
Transitions
At each step, each walker moved either right (same row as before) or down (row one smaller before). That gives four combinations of predecessor:
| Walker 1 came from | Walker 2 came from | Previous state |
|---|---|---|
| left (same row) | left (same row) | `dp[t-1][r1][r2]` |
| above (`r1-1`) | left | `dp[t-1][r1-1][r2]` |
| left | above (`r2-1`) | `dp[t-1][r1][r2-1]` |
| above | above | `dp[t-1][r1-1][r2-1]` |
The recurrence is:
gain = grid[r1][c1] + (grid[r2][c2] if r1 != r2 else 0)
dp[t][r1][r2] = gain + max(four predecessors)Base Case, Boundaries, and Fill Order
- Base case:
dp[0][0][0] = grid[0][0]. Both walkers start on the same cell, so its cherry counts once. - Valid rows at step
t: a rowrneeds0 <= r < nand0 <= t - r < n, sorranges overmax(0, t - n + 1)tomin(n - 1, t). - Thorns: skip any state where either walker stands on
-1. It stays at negative infinity. - Fill order: step
tdepends only on stept - 1, so loop overtfrom outside. You only need two layers, the same rolling-array idea from the one-row chapter. - Answer:
max(0, dp[2n-2][n-1][n-1]). Themax(0, ...)handles a goal that cannot be reached.
Implementation
def cherry_pickup(grid):
n = len(grid)
NEG = float('-inf')
if grid[0][0] == -1:
return 0
dp = [[NEG] * n for _ in range(n)]
dp[0][0] = grid[0][0]
for t in range(1, 2 * n - 1):
new = [[NEG] * n for _ in range(n)]
lo, hi = max(0, t - n + 1), min(n - 1, t)
for r1 in range(lo, hi + 1):
c1 = t - r1
if grid[r1][c1] == -1:
continue
for r2 in range(r1, hi + 1):
c2 = t - r2
if grid[r2][c2] == -1:
continue
best = dp[r1][r2]
if r1 > 0:
best = max(best, dp[r1 - 1][r2])
if r2 > 0:
best = max(best, dp[r1][r2 - 1])
if r1 > 0 and r2 > 0:
best = max(best, dp[r1 - 1][r2 - 1])
if best == NEG:
continue
gain = grid[r1][c1]
if r1 != r2:
gain += grid[r2][c2]
new[r1][r2] = best + gain
dp = new
return max(0, dp[n - 1][n - 1])
print(cherry_pickup([[0, 1, -1], [1, 0, -1], [1, 1, 1]])) # 5
print(cherry_pickup([[1, 1, -1], [1, -1, 1], [-1, 1, 1]])) # 0
print(cherry_pickup([
[1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1],
])) # 15Each step allocates a fresh new layer, so a state that was valid at step t - 1 cannot leak into step t by accident. If you reuse one array in place, the reads of dp[r1][r2] and dp[r1-1][r2] could see values that were already overwritten for the current step.
Complexity
| Version | States | Time | Space |
|---|---|---|---|
| Naive `(r1, c1, r2, c2)` | `n^4` | `O(n^4)` | `O(n^4)` |
| Step-indexed `(t, r1, r2)` | `~2n^3` | `O(n^3)` | `O(n^3)` |
| Step-indexed, two rolling layers | `~2n^3` | `O(n^3)` | `O(n^2)` |
Each state does constant work over four predecessors, so time is proportional to the number of states. With n = 50 that is about 250,000 states before the symmetry saving, which runs quickly in Python.
Common Errors
- Counting a shared cell twice. Forgetting the
r1 != r2check gives totals higher than the number of cherries on the grid. - Letting unreachable states win. If an invalid predecessor holds
0instead of negative infinity, walkers can "teleport" past thorns. Always start with negative infinity and checkbest == NEG. - Returning negative infinity. When thorns block the goal, the final state stays at negative infinity. The problem asks for
0. - Walkers at different steps. If you index walkers separately without a shared
t, you lose the guarantee that shared cells are only met at the same moment, and the single-comparison collision check stops being valid.
A Related Variant
In Cherry Pickup II, two robots start at the top-left and top-right corners. Each moves down one row per step and can shift one column left, stay put, or shift one column right. The row number plays the role of t, so the state is (row, c1, c2) with nine transitions per state. The pattern is the same: a shared clock aligns the walkers, and one comparison detects a shared cell.
Exercise
Why does the solution index walkers by a shared step t instead of letting each walker have its own independent position (r1, c1, r2, c2) visited in any order?
Show answer
Cell (r, c) can only be reached at step r + c. With a shared clock, two walkers can only stand on the same cell at the same step, so "r1 == r2" at step t detects every shared cell. The cherry is then counted once without tracking which cells were already emptied. Using t also cuts the state from n^4 to about 2n^3, because each column follows from t and its row.
Exercise
At step t = 3 in a 3 x 3 grid, which values of r1 are valid, and which cells do they correspond to?
Show answer
Valid rows go from max(0, 3 - 3 + 1) = 1 to min(2, 3) = 2. So r1 = 1 gives cell (1, 2) and r1 = 2 gives cell (2, 1).
Exercise
A teammate changes the recurrence to gain = grid[r1][c1] + grid[r2][c2] with no check. On the grid [[1, 1], [1, 1]], what does the buggy version return, and what is the correct answer?
Show answer
Both walkers count (0, 0) and (1, 1), so the buggy version returns 1 + 1 (start) + 1 + 1 (the two middle cells) + 1 + 1 (goal) = 6. The grid only holds 4 cherries. The correct answer is 4: one walker goes right then down, the other goes down then right, and the shared start and goal count once each.