<p>You are given an <code>n x n</code> <code>grid</code> representing a field of cherries, each cell is one of three possible integers.</p>

<ul>
	<li><code>0</code> means the cell is empty, so you can pass through,</li>
	<li><code>1</code> means the cell contains a cherry that you can pick up and pass through, or</li>
	<li><code>-1</code> means the cell contains a thorn that blocks your way.</li>
</ul>

<p>Return <em>the maximum number of cherries you can collect by following the rules below</em>:</p>

<ul>
	<li>Starting at the position <code>(0, 0)</code> and reaching <code>(n - 1, n - 1)</code> by moving right or down through valid path cells (cells with value <code>0</code> or <code>1</code>).</li>
	<li>After reaching <code>(n - 1, n - 1)</code>, returning to <code>(0, 0)</code> by moving left or up through valid path cells.</li>
	<li>When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell <code>0</code>.</li>
	<li>If there is no valid path between <code>(0, 0)</code> and <code>(n - 1, n - 1)</code>, then no cherries can be collected.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/12/14/grid.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,-1],[1,0,-1],[1,1,1]]
<strong>Output:</strong> 5
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 50</code></li>
	<li><code>grid[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>1</code>.</li>
	<li><code>grid[0][0] != -1</code></li>
	<li><code>grid[n - 1][n - 1] != -1</code></li>
</ul>

class Solution:

    def cherryPickup(self, grid):
        n = len(grid)
        memo = [[[-1] * n for _ in range(n)] for _ in range(n)]
        return max(0, self.dp(grid, memo, 0, 0, 0))
    
    def dp(self, grid, memo, r1, c1, c2):
        n = len(grid)
        r2 = r1 + c1 - c2
        
        # Out of bounds or thorn cell
        if r1 >= n or r2 >= n or c1 >= n or c2 >= n or grid[r1][c1] == -1 or grid[r2][c2] == -1:
            return float('-inf')
        
        # Memoization check
        if memo[r1][c1][c2] != -1:
            return memo[r1][c1][c2]
        
        # Base case: reached bottom-right corner
        if r1 == n - 1 and c1 == n - 1:
            return grid[r1][c1]
        
        # Calculate cherries collected at (r1, c1) and (r2, c2)
        cherries = grid[r1][c1] if r1 == r2 and c1 == c2 else grid[r1][c1] + grid[r2][c2]
        
        # Move right or down
        maxCherries = max(self.dp(grid, memo, r1, c1 + 1, c2), self.dp(grid, memo, r1 + 1, c1, c2))
        # Move down or right
        maxCherries = max(maxCherries, self.dp(grid, memo, r1, c1 + 1, c2 + 1))
        maxCherries = max(maxCherries, self.dp(grid, memo, r1 + 1, c1, c2 + 1))
        
        # Memoize the result
        memo[r1][c1][c2] = maxCherries if maxCherries == float('-inf') else maxCherries + cherries
        
        return memo[r1][c1][c2]
    # this solution doesn't work
    # because local maximum doesn't always help towards cumulative global maximum

    def cherryPickup1(self, grid: List[List[int]]) -> int:
        # determine if we can reach last cell using dp
        # then from last cell, apply dp up to the initial cell
        # to see how many cherries can be picked up

        def get_cherries(grid):
            # -1 means impossible to reach here from start
            # 0 means 0 cherries from start, but valid path
            # otherwise means the number of cherries collected
            dp = [[-1] * len(grid[0]) for _ in range(len(grid))]
            parents = {} # key is (i,j) to indicate child cell, value is (i1,j1) to indicate parent cell
        
            for i in range(len(grid)):
                for j in range(len(grid[0])):
                    if grid[i][j] == -1:
                        continue
                    
                    left = up = 0
                    if i - 1 >= 0:
                        up = dp[i - 1][j]
                    if j - 1 >= 0:
                        left = dp[i][j - 1]
                    if max(left, up) == -1:
                        # both preceding paths are invalid
                        continue

                    if left > up:
                        dp[i][j] = grid[i][j] + left
                        parents[(i, j)] = (i, j - 1)
                    else:
                        dp[i][j] = grid[i][j] + up
                        parents[(i, j)] = (i - 1, j)



            # print(dp)
            return dp[-1][-1], parents

        first_run, parents = get_cherries(grid)
        if first_run <= 0:
            return 0

        # print(parents)
        # remove collected cherries using parents
        i = len(grid) - 1
        j = len(grid[0]) - 1
        while i >= 0 and j >= 0:
            if grid[i][j] == 1:
                grid[i][j] = 0
            i, j = parents[(i, j)]
        
        second_run, dummy = get_cherries(grid)
        return first_run + second_run
        

        


18293