1463. Cherry Pickup II

We are given a grid where each cell represents the number of cherries available. Two robots start at the top-left corner of the grid and must traverse down to the bottom-right corner. Each robot can move only in three directions: down, right, or diagonally down-right. However, the robots cannot occupy the same cell at the same time. The objective is to maximize the total number of cherries collected by both robots.

Approach:

We can solve this problem using dynamic programming. We’ll define a 3D dp array to store the maximum cherries collected by both robots at each position. We’ll then recursively traverse the grid from the top-left corner to the bottom-right corner, considering all possible movements for both robots. We’ll memoize the results to avoid redundant calculations.

Implementation:

We’ll implement the solution in Java using a recursive function traverse to explore all possible movements of the robots. We’ll consider all valid movements for both robots and calculate the maximum cherries collected. We’ll memoize the results using the dp array to optimize the solution.

class Solution {
    int dp[][][];
    
    public int cherryPickup(int[][] grid) {
        dp = new int[grid.length][grid[0].length][grid[0].length];
        for(int i=0;i<grid.length;i++) {
            for(int j=0;j<grid[0].length;j++) {
                for(int k=0;k<grid[0].length;k++) {
                    dp[i][j][k] = -1;
                }
            }
        }
        return traverse(0, 0, grid[0].length-1, grid);
    }
    
    public int traverse(int roboRow1, int roboCol1, int roboCol2, int[][] grid) {
        if (roboRow1 >= grid.length || roboCol1 >= grid[0].length
            || roboCol2 >= grid[0].length || roboCol1 < 0 || roboCol2 < 0) {
            return 0;
        }
        if (dp[roboRow1][roboCol1][roboCol2] != -1) {
            return dp[roboRow1][roboCol1][roboCol2];
        }
        int columnDir[] = new int[]{-1, 0, 1};
        int max = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int temp = traverse(roboRow1+1, roboCol1 + columnDir[i], roboCol2 + columnDir[j], grid);
                max = Math.max(max, temp);
            }
        }
        if (roboCol1 != roboCol2) {
            max += (grid[roboRow1][roboCol1] + grid[roboRow1][roboCol2]);
        } else {
            max += grid[roboRow1][roboCol1];
        }
        dp[roboRow1][roboCol1][roboCol2] = max;
        return max;
    }
}

Conclusion:

In this blog post, we discussed the problem of maximizing cherry pickup in a grid using a dynamic programming approach. We provided an overview of the problem statement, explained the approach, and provided a detailed implementation in Java. By understanding this solution, you can efficiently solve similar optimization problems involving grid traversal and dynamic programming.

Related Post