当前位置: 代码迷 >> 综合 >> leetcode:1219. 黄金矿工(dfs)
  详细解决方案

leetcode:1219. 黄金矿工(dfs)

热度:79   发布时间:2024-02-09 13:15:09.0

链接:https://leetcode-cn.com/problems/path-with-maximum-gold/
dfs即可,注意dfs时不能重复进入一个矿洞。
C++代码:

class Solution {
public:int getMaximumGold(vector<vector<int>>& grid) {int res = 0;for(int i = 0;i<grid.size();i++){for(int j = 0;j<grid[0].size();j++){if(grid[i][j]!=0){res = max(res,dfs(grid,i,j,0));}}}return res;}int dfs(vector<vector<int>>& grid, int i,int j,int sum){if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||grid[i][j]==0)return sum;int temp = grid[i][j];grid[i][j] = 0;int temp1 = max(dfs(grid,i-1,j,sum+temp),dfs(grid,i+1,j,sum+temp));int temp2 = max(dfs(grid,i,j-1,sum+temp),dfs(grid,i,j+1,sum+temp));grid[i][j] = temp;return max(temp1,temp2);}
};