Cherry Pickup

In a N x N grid representing a field of cherries, each cell is one of three possible integers.

 

 

Your task is to collect maximum number of cherries possible by following the rules below:

 

 

 

Example 1:

Input: grid =
[[0, 1, -1],
 [1, 0, -1],
 [1, 1,  1]]
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.

 

Note:


Solution:

class Solution {
    Map<Integer, Integer> memo = new HashMap();
    
    public int cherryPickup(int[][] grid) {
        int n = grid.length;
        int sum = bt(grid, 0, 0, 0, 0);
        return sum > 0 ? sum : 0;
    }
    
    private int bt(int[][] grid, int x1, int y1, int x2, int y2) {
        int n = grid.length;
        if (x1 == n - 1 && y1 == n - 1) {
            if (grid[x1][y1] == -1) return Integer.MIN_VALUE;
            else return grid[x1][y1];
        };
        if (x1 >= n || y1 >= n || x2 >= n || y2 >= n || grid[x1][y1] == -1 || grid[x2][y2] == -1) {
            return Integer.MIN_VALUE;
        }
        int hashCode = hash(x1, y1, x2, y2);
        if (memo.containsKey(hashCode)) return memo.get(hashCode);
        int curr = 0;
        if (x1 == x2 && y1 == y2) {
            curr = grid[x1][y1];
        } else {
            curr = grid[x1][y1] + grid[x2][y2];
        }
        int next = Math.max(bt(grid, x1 + 1, y1, x2 + 1, y2), bt(grid, x1, y1 + 1, x2, y2 + 1));
        next = Math.max(next, bt(grid, x1 + 1, y1, x2, y2 + 1));
        next = Math.max(next, bt(grid, x1, y1 + 1, x2 + 1, y2));
        memo.put(hashCode, curr + next);
        return curr + next;
    }
    
    private int hash(int x1, int y1, int x2, int y2) {
        int hash = 17;
        hash = 31 * hash + x1;
        hash = 137 * hash + y1;
        hash = 131 * hash + x2;
        hash = 37 * hash + y2;
        return hash;
    }
}