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