链接: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);}
};