You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,1 means the cell contains a cherry that you can pick up and pass through, or-1 means the cell contains a thorn that blocks your way.Return the maximum number of cherries you can collect by following the rules below:
(0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).(n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.0.(0, 0) and (n - 1, n - 1), then no cherries can be collected.Output: 5
Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Output: 0
n == grid.lengthn == grid[i].length1 <= n <= 50grid[i][j] is -1, 0, or 1.grid[0][0] != -1grid[n - 1][n - 1] != -1The idea is to use a recursive approach, trying to solve the problem by walking from the top-left to the bottom-right and then back again. Since there are two distinct paths (forward and backward), the problem can be visualized like two people moving simultaneously across the grid.
maxCherries(r1, c1, r2, c2) where r1, c1 are the row and column for the first person, and r2, c2 for the second person.The recursive method will be inefficient for larger grids due to redundant calculations. Dynamic Programming (DP) allows us to break down the problem into smaller overlapping subproblems, caching results and reusing them.
dp[r1][c1][r2] represents the maximum number of cherries both persons can pick starting from cell (r1, c1) and (r2, c2) respectively to cell (n-1, n-1) and back.(n-1, n-1) where if both arrive together at this point, they can pick the cherries there only once.In this enhanced variation, we reduce the space complexity further by understanding that only the immediate previous row states are needed to compute the current row state in a 2D traversal.
Use only a 2D DP array, reducing space complexity but altering our method to fit inline with computed states.