1
var getMaximumGold = function (grid) {
2
let max = 0;
3

4
// This is our internal dfs function that will search all possible directions from a cell
5
const mine = (x, y, n) => {
6
// We can't mine any gold if the position is out of the grid, or the cell doesnt have any gold
7
if (
8
x < 0 ||
9
y < 0 ||
10
x > grid.length - 1 ||
11
y > grid[x].length - 1 ||
12
grid[x][y] == 0
13
)
14
return 0;
15

16
// Save the temp value so we can mark the cell as visited
17
let temp = grid[x][y];
18
grid[x][y] = 0;
19

20
// Try mining left, right, up, and down from the current position,
21
// bringing along the gold total that was found in the current cell
22
mine(x + 1, y, n + temp);
23
mine(x - 1, y, n + temp);
24
mine(x, y + 1, n + temp);
25
mine(x, y - 1, n + temp);
26

27
// After we've tried all directions reset cell to have its original value,
28
// so it can be mined from a different starting point
29
grid[x][y] = temp;
30

31
// Update the max based on the mining done up until the current cell
32
max = Math.max(max, n + temp);
33
};
34

35
// We need to run this dfs function through every potential starting point
36
for (let i = 0; i < grid.length; i++) {
37
for (let j = 0; j < grid[i].length; j++) {
38
mine(i, j, 0);
39
}
40
}
41
return max;
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0