-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec10_37.cpp
75 lines (61 loc) Β· 1.97 KB
/
lec10_37.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
73
74
75
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int f(int i, int j1, int j2, int r, int c, vector<vector<int>>& grid, vector<vector<vector<int>>> &dp) {
if (j1 < 0 || j2 < 0 || j1 >= c || j2 >= c) {
return -1e9; // Large negative value for invalid states
}
if (i == r - 1) { // Base case: Last row
if (j1 == j2) return grid[i][j1];
else return grid[i][j1] + grid[i][j2];
}
if( dp[i][j1][j2] !=-1) return dp[i][j1][j2];
int maxi = -1e9; // Maximum value from all paths
for (int dj1 = -1; dj1 <= 1; dj1++) {
for (int dj2 = -1; dj2 <= 1; dj2++) {
int value = 0;
if (j1 == j2)
value = grid[i][j1]; // Both are at the same cell
else
value = grid[i][j1] + grid[i][j2]; // Different cells
value += f(i + 1, j1 + dj1, j2 + dj2, r, c, grid , dp);
maxi = max(maxi, value);
}
}
return dp[i][j1][j2] =maxi;
}
int solve(int r, int c, vector<vector<int>>& grid) {
// code here
// int dp[r][c][c];
vector<vector<vector<int>>> dp( r ,vector<vector<int>>( c , vector<int>(c , -1)));
return f(0, 0, c - 1, r, c, grid ,dp);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<int>> grid;
for (int i = 0; i < n; i++) {
vector<int> temp;
for (int j = 0; j < m; j++) {
int x;
cin >> x;
temp.push_back(x);
}
grid.push_back(temp);
}
Solution obj;
cout << obj.solve(n, m, grid) << "\n";
cout << "~"
<< "\n";
}
return 0;
}
// } Driver Code Ends