func goldRush(gMap Map) int {
max := 0
for i, col := range gMap {
for j, _ := range col {
max = variadicMax(max, goldRushPath(gMap, i, j, 0))
}
}
return max
}
func goldRushPath(gMap Map, x, y, sum int) int {
if x < 0 || y < 0 || x >= len(gMap) || y >= len(gMap[0]) || gMap[x][y] == 0 {
return sum
}
sum += gMap[x][y]
defer (func(val int) { gMap[x][y] = val })(gMap[x][y])
gMap[x][y] = 0
return variadicMax(
goldRushPath(gMap, x+1, y, sum),
goldRushPath(gMap, x-1, y, sum),
goldRushPath(gMap, x, y+1, sum),
goldRushPath(gMap, x, y-1, sum),
)
}
#Challenge
Source | Language |
---|---|
DailyByte | go |
#Solution
Given a 2D matrix representing a gold mine, where each cells value represents an amount of gold, return the maximum amount of gold you can collect given the following rules:
- You may start or stop collecting gold at any poisition.
- You can never visit a cell containing 0 gold.
- You cannot visit the same cell more than once.
- FRom the current cell you may walk one cell left, right, up or down.
For example, given the following gold mine:
[0 2 0]
[8 6 3]
[0 9 0]
We should get 23 (starting from 9, moving to 6 then 8 respectively).
#Utils
type Map = [][]int
func variadicMax(nums ...int) int {
if len(nums) == 0 {
panic("must provide at least one num")
}
val := 0
for _, num := range nums {
if num > val {
val = num
}
}
return val
}