Skip to content

Commit a9be3c1

Browse files
authored
Create 1219-path-with-maximum-gold.js
1 parent 869784e commit a9be3c1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

1219-path-with-maximum-gold.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const getMaximumGold = function(grid) {
6+
const m = grid.length, n = grid[0].length
7+
const arr = []
8+
const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
9+
const visited = new Set()
10+
for(let i = 0; i < m; i++) {
11+
for(let j = 0; j < n; j++) {
12+
if(grid[i][j] !== 0) arr.push([i, j])
13+
}
14+
}
15+
let res = 0
16+
17+
for(const [i, j] of arr) {
18+
visited.clear()
19+
visited.add(`${i},${j}`)
20+
dfs(i, j, grid[i][j])
21+
}
22+
23+
return res
24+
25+
function dfs(i, j, cur) {
26+
27+
res = Math.max(res, cur)
28+
for(const [dx, dy] of dirs) {
29+
const nx = i + dx
30+
const ny = j + dy
31+
const key = `${nx},${ny}`
32+
if(nx >= 0 && nx < m && ny >= 0 && ny < n && !visited.has(key) && grid[nx][ny] !== 0) {
33+
visited.add(key)
34+
dfs(nx, ny, cur + grid[nx][ny])
35+
visited.delete(key)
36+
}
37+
}
38+
}
39+
40+
};

0 commit comments

Comments
 (0)