1
0
Fork 0
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:
Matej Focko 2024-05-15 15:37:33 +02:00
parent 7675c66d38
commit 590fe65d50
Signed by: mfocko
GPG key ID: 7C47D46246790496

View 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;
}
}