你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0。
为了使收益最大化,矿工需要按以下规则来开采黄金:
每当矿工进入一个单元,就会收集该单元格中的所有黄金。
矿工每次可以从当前位置向上下左右四个方向走。
每个单元格只能被开采(进入)一次。
不得开采(进入)黄金数目为 0 的单元格。
矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。
题目:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-with-maximum-gold
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
int ans = 0;//结果
public int getMaximumGold(int[][] grid) {
Deque<Integer> gets = new ArrayDeque<>();//用于存放已经带上的黄金
for (int i = 0; i < grid.length; i++) {//遍历每一行
for (int j = 0; j < grid[0].length; j++) {//遍历每一行元素
dfs(grid,0,gets,i,j);
}
}
return ans;
}
public void dfs(int[][] grid,int temp,Deque<Integer> gets,int x,int y){
//选择
if (x>=grid.length || x<0 || y>=grid[0].length || y<0)//不能超出范围
return;
else {
if (grid[x][y] != 0){
gets.addLast(grid[x][y]);//进栈且令其暂时为0
temp += grid[x][y];//为0前先将其值加入temp
grid[x][y] = 0;
if (temp > ans) ans = temp;
//递归
dfs(grid,temp,gets,x-1,y);//上
dfs(grid, temp, gets, x+1, y);//下
dfs(grid, temp, gets, x, y-1);//左
dfs(grid, temp, gets, x, y+1);//右
grid[x][y] = gets.removeLast();//出栈,撤回
temp -= grid[x][y];
}
}
return;
}
}