Sub topic 16
Two Walkers at Once: Cherry Pickup
This chapter assumes you are comfortable with minimum-cost grid DP, fill order, and complexity analysis from earlier chapters. Here the state has to describe two positions at once, which raises the dimension of the table.
The Problem
You get an n x n grid. A cell holds 1 (a cherry), 0 (empty), or -1 (a thorn you cannot enter). You walk from (0, 0) to (n-1, n-1) moving only right or down. Then you walk back moving only left or up. You collect every cherry you pass, and a picked cell becomes empty. What is the most cherries you can collect? If no path exists, the answer is 0.
A common mistake is to run the best single path, remove its cherries, and then run the best path again. That greedy approach can fail. The first path may take cherries in a way that leaves the second path with nothing, when two balanced paths would collect more in total.
Reframing: Two Walkers Going Forward
A return trip that moves left or up is the same as a forward trip played in reverse. So the problem becomes: two walkers start at (0, 0) together and both move right or down to (n-1, n-1). When both walkers stand on the same cell, its cherry counts once.
If both walkers move in lockstep, after t steps each one satisfies row + col = t. That means three numbers describe the whole situation:
t, the step numberr1, the row of walker 1, soc1 = t - r1r2, the row of walker 2, soc2 = t - r2
dp[t][r1][r2] is the most cherries collected when the walkers stand at (r1, t-r1) and (r2, t-r2), or minus infinity if that position pair cannot be reached.
The Recurrence
Each walker came either from above (row minus 1) or from the left (row unchanged). That gives four predecessor states:
The update takes the best of the four and adds grid[r1][c1], plus grid[r2][c2] only when r1 != r2. On a given step, equal rows mean the same cell. Because dp[t] depends only on dp[t-1], you can keep a single 2D layer of size n x n, the same rolling idea you used to shrink a table to one row.
Implementation
def cherry_pickup(grid):
n = len(grid)
NEG = float('-inf')
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(lo, 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]])) # 5The lo/hi bounds keep both columns inside the grid, so the code never reads out of range. Using minus infinity for unreachable states stops thorn-blocked routes from feeding into the answer.
Cost
| Measure | Value | Reason |
|---|---|---|
| States | O(n³) | about 2n steps × n × n row pairs |
| Time | O(n³) | constant work per state |
| Space | O(n²) | one rolling layer per step |
Exercise
Why does the code add grid[r2][c2] only when r1 != r2, and why is comparing rows alone enough to detect a shared cell?
Show answer
A cherry can be picked only once, so when both walkers stand on the same cell its value must be added a single time. Both walkers satisfy row + col = t on the same step, so equal rows force equal columns. Equal rows therefore mean the same cell.
Exercise
Give a reason the greedy "best path, clear it, best path again" strategy can do worse than the two-walker DP.
Show answer
The first greedy path maximizes only its own total. It can take cherries from two separate regions in a way that leaves the second pass with few or none. The joint DP looks at both paths together and can split those regions between the walkers, which gives a larger total.