<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:
    # https://leetcode.com/problems/cherry-pickup/solutions/3811789/dp-and-dfs-solutions-with-a-different-and-hopefully-simpler-explanations-ft-100/
    def cherryPickup(self, grid: List[List[int]]) -> int:
        # 主要数据结构分析：
        # dfs的三个参数：k是走过的步数，r1和r2分别是走过了几行（注意k-r1和r2就是走过的列数）
        bad = float('-inf')

        @functools.cache
        def dfs(k: int, r1: int, r2: int):
            # 这道题的关键是：
            # * 想到2条路同时dfs这种方案（需要四种回溯）
            # * 而且要能想到两条路同时从上往下和一次向下一次向上都是一样的结果（因为是同一个path）
            # * 而且两次简单的DP不能解决问题（他并没有解释只是说两次greedy不见得是答案）
            # print(r1, k-r1, r2, k-r2)
            # 为什么r1 > r2是非法？答案是没有必要检查 r1 > r2
            if r1 < 0 or r2 < 0:
                return bad

            c1 = k-r1
            c2 = k-r2

            if c1 < 0 or c2 < 0:
                return bad

            # 问题：k == 0能保证走到了(0,0)这个点么？答案是可以，因为无论r1,r2还是c1,c2都不可以小于0，那么只能都等于0了
            if k == 0:
                return grid[0][0] # first step, r1 == .. == c2 == 0

            if grid[r1][c1] < 0 or grid[r2][c2] < 0:
                return bad

            prev = max(
                dfs(k-1, r1, r2),
                dfs(k-1, r1-1, r2),
                dfs(k-1, r1, r2-1),
                dfs(k-1, r1-1, r2-1)
            )

            # 之所以上面返回float('-inf')是为了方便这里
            # 如果四条路都返回-inf，那么无论当前怎么样最终还是-inf
            # 注意r1 == r2保证了不会同一个格子取两次樱桃（而且这个必须是两条路同时往下走的情况，如果一个向上一个向下就很难搞了）
            if r1 == r2:
                return prev + grid[r1][c1]
            else:
                return prev + grid[r1][c1] + grid[r2][c2]

        N = len(grid)
        return max(dfs(2*N-2, N-1, N-1), 0)
60626