forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
36 lines (36 loc) · 1.25 KB
/
Solution.java
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
class Solution {
public int cherryPickup(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] f = new int[n][n];
int[][] g = new int[n][n];
for (int i = 0; i < n; ++i) {
Arrays.fill(f[i], -1);
Arrays.fill(g[i], -1);
}
f[0][n - 1] = grid[0][0] + grid[0][n - 1];
for (int i = 1; i < m; ++i) {
for (int j1 = 0; j1 < n; ++j1) {
for (int j2 = 0; j2 < n; ++j2) {
int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]);
for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) {
for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) {
if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) {
g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x);
}
}
}
}
}
int[][] t = f;
f = g;
g = t;
}
int ans = 0;
for (int j1 = 0; j1 < n; ++j1) {
for (int j2 = 0; j2 < n; ++j2) {
ans = Math.max(ans, f[j1][j2]);
}
}
return ans;
}
}