source: https://leetcode.com/problems/cherry-pickup-ii/description/
Cherry Pickup II
You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner (0, cols – 1).
Return the maximum number of cherries collection using both robots by following the rules below:
From a cell (i, j), robots can move to cell (i + 1, j – 1), (i + 1, j), or (i + 1, j + 1).
When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
When both robots stay in the same cell, only one takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in grid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Solution { public int cherryPickup(int[][] grid) { int[] p1 = {0, 0}; int[] p2 = {0, grid[0].length-1}; int[][][] memo = new int[grid.length][grid[0].length][grid[0].length]; for(int[][] m: memo){ for(int[] n: m){ Arrays.fill(n, -1); } } return dfs(grid, p1, p2, memo); } private int dfs(int[][] grid, int[] p1, int[] p2, int[][][] memo){ int[] c = {-1, 0, 1}; int max = Integer.MIN_VALUE; int result = 0; if(!isValid(grid, p1) || !isValid(grid, p2)){ return 0; } if(memo[p1[0]][p1[1]][p2[1]]!=-1){ return memo[p1[0]][p1[1]][p2[1]]; } result = result + grid[p1[0]][p1[1]]; if(p1[1]!=p2[1]){ result = result + grid[p2[0]][p2[1]]; } for(int i=0;i<c.length;i++){ for(int j=0;j<c.length;j++){ max = Math.max(max, result + dfs(grid, new int[]{p1[0]+1, p1[1]+c[i]}, new int[]{p2[0]+1, p2[1]+c[j]}, memo)); } } memo[p1[0]][p1[1]][p2[1]] = max; return max; } private boolean isValid(int[][] grid, int[] p){ return p[0] < grid.length && p[1] >=0 && p[1] < grid[0].length; } } |