forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCherry Pickup.cpp
72 lines (56 loc) · 1.81 KB
/
Cherry Pickup.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution {
public:
int solve(int r1,int c1,int r2,vector<vector<int>>& grid, vector<vector<vector<int>>> &dp)
{
//Calculating c2 :
/*
(r1 + c1) = (r2 + c2)
c2 = (r1 + c1) - r2
*/
int c2 = (r1+c1)-r2 ;
//Base condition
if(r1 >= grid.size() || r2 >= grid.size() || c1 >= grid[0].size() || c2 >= grid[0].size() || grid[r1][c1] == -1 || grid[r2][c2] == -1)
{
return INT_MIN;
}
if(r1 == grid.size()-1 && c1 == grid[0].size()-1)
{
return grid[r1][c1] ;
}
if(dp[r1][c1][r2] != -1)
{
return dp[r1][c1][r2];
}
int ch = 0;
if(r1 == r2 && c1 == c2)
{
ch += grid[r1][c1];
//if both players are at the same place than collect cherry only one time.
}
else
{
ch += grid[r1][c1] + grid[r2][c2];
}
cout<<ch<<"\n";
//Trying all the possible paths for both the players
int hh = solve(r1, c1+1, r2, grid, dp);
int vh = solve(r1+1, c1, r2, grid, dp);
int vv = solve(r1+1, c1, r2+1, grid, dp);
int hv = solve(r1, c1+1, r2+1, grid, dp);
//collecting maximum cherries from possible paths
ch += max(max(hh, vh),max(vv, hv)) ;
dp[r1][c1][r2] = ch;
return ch;
}
int cherryPickup(vector<vector<int>>& grid)
{
int n = grid.size();
vector<vector<vector<int>>>dp(n, vector<vector<int>>(n, vector<int>(n,-1)));
int ans = solve(0,0,0,grid,dp) ;
if(ans == INT_MIN || ans <0)
{
return 0;
}
return ans;
}
};