http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/
Problem:
In a N x N grid
representing a field of cherries, each cell is one of three possible integers.
- 0 means the cell is empty, so you can pass through;
- 1 means the cell contains a cherry, that you can pick up and pass through;
- -1 means the cell contains a thorn that blocks your way.
Your task is to collect maximum number of cherries possible by following the rules below:
- Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);
- After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;
- When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);
- If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.
题目大意:给你樱桃田的地图(1: 樱桃, 0: 空, -1: 障碍物)。然你从左上角走到右下角(只能往右或往下),再从右下角走回左上角(只能往左或者往上)。问你最多能采到多少棵樱桃。
思路:
动态规划
关键点: 从(0,0) 到 (n-1, n-1) 再回到 (0, 0) 相当于两次从 (n-1,n-1) 到 (0,0)
- 想象有两个人从(n-1, n-1) 到(0, 0).
- 两人同时(向左或向上)移动一格,当格子上有草莓时将其捡起.
- 如果两人移动到同一个格子,并且格子上有草莓时,仅有一人能捡到草莓.
方案: DP / Recursion with memoization.
dp(x1, y1, x2,y2) 表示从两个人分别从(x1, y1), (x2, y2) 到(0,0)捡到的最大草莓数。
因为两个人同时从同一点出发,其移动的步数相同,即 x1+y1 =x2 + y2 => y2 = x1+y1-x2, 那么dp(x1,y1,x2,y2)可以由dp(x1,y1,x2)来表示。
class Solution {
private int[][][] m_;
public int cherryPickup(int[][] grid) {
int N = grid.length;
m_ = new int[N][N][N];
for(int i = 0; i < N; i++){
for(int j =0; j < N; j++){
for(int k = 0; k < N; k++){
m_[i][j][k] = Integer.MIN_VALUE;
}
}
}
return Math.max(0, dp(N-1, N-1, N-1, grid));
}
private int dp(int x1, int y1, int x2, int[][] grid){
int y2 = x1 + y1 - x2;
if(x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0) return -1;
if(grid[y1][x1] < 0 || grid[y2][x2] < 0) return -1;
if (x1 == 0 && y1 == 0) return grid[y1][x1];
if (m_[x1][y1][x2] != Integer.MIN_VALUE) return m_[x1][y1][x2];
int ans = Math.max(Math.max(dp(x1-1, y1, x2-1, grid), dp(x1, y1-1, x2, grid)),
Math.max(dp(x1, y1-1, x2-1, grid), dp(x1-1, y1, x2, grid)));
if (ans < 0) {
m_[x1][y1][x2] = -1;
return m_[x1][y1][x2];
}
ans += grid[y1][x1];
if (x1 != x2) ans += grid[y2][x2];
m_[x1][y1][x2] = ans;
return ans;
}
}