Problem Description
Given an n x n grid where each cell is either 0 (empty), 1 (cherry), or -1 (thorn), the goal is to collect the maximum cherries possible. Start at (0,0) and move to (n-1,n-1) by only moving right or down. Then, return to (0,0) by moving left or up. When a cherry is collected, the cell becomes 0. If there is no valid path between (0,0) and (n-1,n-1), return 0.
Key Insights
- Transforming the two trips (out and back) into one simultaneous traversal by having two agents start at (0,0) and move to (n-1,n-1) concurrently.
- Since both agents make the same number of moves, their positions satisfy r1+c1 = r2+c2, which allows reducing the state dimension.
- Use dynamic programming with a 3-dimensional state (r1, c1, r2) while computing c2 as (r1+c1-r2).
- Avoid double counting the cherry if both agents land on the same cell.
- Return 0 if no valid path exists (i.e. if the computed maximum is negative).
Space and Time Complexity
Time Complexity: O(n^3) where n is the grid dimension. Space Complexity: O(n^3) for the DP memoization table.
Solution
The solution employs a dynamic programming approach by simulating two agents moving simultaneously from the start to the destination. Each state is defined by (r1, c1, r2) with c2 computed from the invariant r1+c1 = r2+c2. The algorithm explores all the valid combinations of right and down moves for both agents. When both agents are on the same cell, its cherry (if present) is only counted once. If any move leads to an invalid cell or a thorn, that path is considered as -infinity. A memoization table caches computed states to avoid redundant calculations. The final answer is the maximum cherries collected along the optimal path from start to finish, or 0 if no valid path exists.