力扣 - 1219. 黄金矿工

思路 :  

          本题要找到获取到 黄金的最大价值,也就是找到一条 连续的每一个节点不为0的路径相加和的最大值。

        那需要解决两个问题: 

                 1、如何确定 起始点  ->  把每一个位置 都当作起始点 

                 2、每一步如何进行移动 ->   主要移动有 上下左右 四个方向。通过回溯、递归的方式 找到一个最大值。

          

// 此位置 方向 目录 
var dirs = []struct{x, y int}{{-1, 0}, {1, 0}, {0, 1}, {0, -1}} func getMaximumGold(grid [][]int) (res int) { if len(grid) == 0 { return } // 如何找到 最优的路线 // 如何找到 起始点 -> 类似于 这种 如果有多个起点 那就是 回溯的方式 var dps func(x, y, capValue int) dps = func(x, y, capValue int) {           
// 每一个递归都进行 相加 判断 是否大于 全部变量 进行赋值即可 capValue += grid[x][y] if capValue > res { res = capValue } // 防止递归遍历在 不为0的路上 所以需要进行 记录原始值 originValue := grid[x][y]
// 将当前 走的位置 设置为 0 grid[x][y] = 0 // 循环上下左右 四个方向 for _, dir := range dirs { // 在原始的左边进行相加 newX, newY := x + dir.x, y + dir.y if newX >= 0 && newX < len(grid) && newY >= 0 && newY < len(grid[newX]) && grid[newX][newY] > 0 { dps(newX, newY, capValue) } }
// 在进行完成此条路径之后 将每一个位置的数字进行还原 进行下次递归 grid[x][y] = originValue } for i:=0;i<len(grid);i++{ for j:=0;j<len(grid[i]);j++{ if grid[i][j] > 0 { dps(i, j, 0) } } } return }
posted @ 2023-01-21 14:13  Black_Climber  阅读(17)  评论(0编辑  收藏  举报