Three coordinates can describe two travelers
Picture
Two robots start at opposite ends of the top row. Each moves down one row per turn, shifting left, staying in its column, or shifting right. To maximize collected values, you need both column positions. Their row is shared because they move in synchrony.
Predict
Do you need (row1, col1, row2, col2), or can one coordinate be removed? If both robots occupy the same square, should its value count twice?
Reveal the reasoning
The rows are equal by the movement rule, so (row, col1, col2) is enough. Count a shared square once when the task says values are collected only once.
Go deeper: derive what is independent
Let best(r,a,b) return the maximum value collected from row r onward when the robots are about to collect columns a and b. The grid is nonempty and rectangular in the recurrence; the wrapper handles empty input.
from functools import cache
def collect(grid):
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
@cache
def best(r, a, b):
if r == rows:
return 0
gain = grid[r][a] + (grid[r][b] if a != b else 0)
future = max(best(r + 1, na, nb)
for na in range(max(0, a - 1), min(cols, a + 2))
for nb in range(max(0, b - 1), min(cols, b + 2)))
return gain + future
return best(0, 0, cols - 1)
assert collect([[1, 2, 3], [0, 5, 0]]) == 9
assert collect([[4], [7]]) == 11
assert collect([[-2]]) == -2
On the two-row example, the starting gain is 1+3=4. Both can reach the middle value 5, but it contributes only once, giving 9 total.
Each state has at most nine joint moves, three choices per robot. There are at most R·C² states: O(RC²) time with the constant nine made explicit, O(RC²) cache space, and O(R) stack depth. Out-of-range moves are excluded rather than assigned zero; returning zero for an invalid move could incorrectly beat a valid negative-valued route.
Why no set of previously collected cells? Rows strictly increase, so no future row has been collected. History affects only the current positions. If upward moves were allowed, that would need reconsideration.
Analogy limit: counting visible objects is not counting state dimensions. Derived coordinates should not be stored merely because they appear in the story.
Change one rule
One robot may wait while the other moves down. Can you still assume the rows match?
Check the variation
No. The synchronization guarantee is gone. You need enough information to recover both positions, and must reconsider collection history and termination rules as well.
Connect
Compression can retain only the next row’s column-pair layer. Tree DP also combines conditional alternatives. Subset DP stores history when it cannot be summarized by positions alone.