mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «1219. Path with Maximum Gold»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
7675c66d38
commit
590fe65d50
1 changed files with 44 additions and 0 deletions
44
java/path-with-maximum-gold.java
Normal file
44
java/path-with-maximum-gold.java
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
class Solution {
|
||||||
|
private int dfs(int[][] grid, int x, int y) {
|
||||||
|
int rows = grid.length;
|
||||||
|
int cols = grid[0].length;
|
||||||
|
|
||||||
|
// BASE: out of bounds
|
||||||
|
if (y < 0 || y >= rows || x < 0 || x >= cols) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// BASE: nothing to collect
|
||||||
|
if (grid[y][x] == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int found = 0;
|
||||||
|
|
||||||
|
int current = grid[y][x];
|
||||||
|
|
||||||
|
grid[y][x] = 0;
|
||||||
|
for (int d = -1; d <= 1; d += 2) {
|
||||||
|
found = Math.max(found, dfs(grid, x + d, y));
|
||||||
|
found = Math.max(found, dfs(grid, x, y + d));
|
||||||
|
}
|
||||||
|
grid[y][x] = current;
|
||||||
|
|
||||||
|
return found + current;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaximumGold(int[][] grid) {
|
||||||
|
int rows = grid.length;
|
||||||
|
int cols = grid[0].length;
|
||||||
|
|
||||||
|
int maxGoldFound = 0;
|
||||||
|
for (int i = 0; i < rows * cols; ++i) {
|
||||||
|
int y = i / cols;
|
||||||
|
int x = i % cols;
|
||||||
|
|
||||||
|
maxGoldFound = Math.max(maxGoldFound, dfs(grid, x, y));
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxGoldFound;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue