-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxgold.java
36 lines (29 loc) · 974 Bytes
/
maxgold.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 {
int[] roww = {1, -1, 0, 0};
int[] coll = {0, 0, -1, 1};
int maxGold = 0;
public int dfs(int[][] grid, int x, int y, int n, int m) {
if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0) return 0;
int curr = grid[x][y];
grid[x][y] = 0;
int localMaxGold = curr;
for (int i = 0; i < 4; i++) {
int newX = x + roww[i];
int newY = y + coll[i];
localMaxGold = Math.max(localMaxGold, curr + dfs(grid, newX, newY, n, m));
}
grid[x][y] = curr;
return localMaxGold;
}
public int getMaximumGold(int[][] grid) {
int n = grid.length, m = grid[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] != 0) {
maxGold = Math.max(maxGold, dfs(grid, i, j, n, m));
}
}
}
return maxGold;
}
}