-
Notifications
You must be signed in to change notification settings - Fork 0
/
1219-getMaximumGold.go
60 lines (54 loc) · 1.01 KB
/
1219-getMaximumGold.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// https://leetcode-cn.com/problems/path-with-maximum-gold/
package main
import "fmt"
/**
* 有想到递归,但没想好怎么实现
* 下面看参考答案的
*/
var dirs = []struct{ x, y int }{
{-1, 0}, // 上
{1, 0}, // 下
{0, -1}, // 左
{0, 1}, // 右
}
func getMaximumGold(grid [][]int) (ans int) {
var dfs func(x, y, gold int)
dfs = func(x, y, gold int) {
gold += grid[x][y]
if gold > ans {
ans = gold
}
rec := grid[x][y]
grid[x][y] = 0 // 标记已开采过
for _, d := range dirs {
nx, ny := x+d.x, y+d.y
if 0 <= nx && nx < len(grid) && 0 <= ny && ny < len(grid[nx]) && grid[nx][ny] > 0 {
dfs(nx, ny, gold)
}
}
grid[x][y] = rec // 恢复
}
for i, row := range grid {
for j, gold := range row {
if gold > 0 {
dfs(i, j, 0)
}
}
}
return
}
func main() {
grid := [][]int{
{0, 6, 0},
{5, 8, 7},
{0, 9, 0},
}
grid2 := [][]int{
{1, 0, 7},
{2, 0, 6},
{3, 4, 5},
{0, 3, 0},
{9, 0, 20},
}
fmt.Println(getMaximumGold(grid), getMaximumGold(grid2))
}