1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/path-with-maximum-gold.java
Matej Focko 590fe65d50
java: add «1219. Path with Maximum Gold»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-05-15 15:37:33 +02:00

44 lines
912 B
Java

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