-
Notifications
You must be signed in to change notification settings - Fork 0
/
1219. Path with maximum gold
73 lines (54 loc) · 1.46 KB
/
1219. Path with maximum gold
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
//1219. Path with maximum gold
class Solution {
public int max = 0;
public void ways(int[][] grid,int r, int c, int gold){
if(gold > max) {
max = gold;
}
if(grid[r][c] == 0) {
return;
}
int a = grid[r][c];
grid[r][c] = 0;
if(r - 1 >= 0) {
ways(grid, r - 1, c, gold + a);
}
if(r + 1 <= grid.length - 1) {
ways(grid, r + 1, c, gold + a);
}
if(c + 1 <= grid[0].length - 1) {
ways(grid, r, c + 1, gold + a);
}
if(c - 1 >= 0) {
ways(grid, r, c - 1, gold + a);
}
grid[r][c] = a;
return ;
}
public int gridWithNoZeros(int[][] grid){
int count = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == 0) {
return -1;
}
else {
count += grid[i][j];
}
}
}
return count;
}
public int getMaximumGold(int[][] grid) {
int count = gridWithNoZeros(grid);
if(count != -1) {
return count;
}
for(int i = 0; i < grid.length; i ++) {
for(int j = 0 ; j < grid[0].length ; j++) {
ways(grid, i, j, 0);
}
}
return max;
}
}