Well, it's a recursion.
Judgment end condition: all around.
So according to this idea, first judge whether there are numbers around, and then judge whether it is 0.
Is 0, go in the next direction; not zero, recursive. In the end, there will always be cases where the surroundings are all 0, and at this time, the maximum value is judged.
class Solution {
public:
int max_=0;
int px[4]={0,0,-1,1};
int py[4]={1,-1,0,0};
int getMaximumGold(vector<vector<int>>& grid) {
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
if(grid[i][j]!=0) {
int tep=grid[i][j];
grid[i][j]=0;
dfs(grid,i,j,tep);
grid[i][j]=tep;
}
}
}
return max_;
}
void dfs(vector<vector<int>>& grid,int x,int y,int sum){
int row=grid.size();
int col=grid[0].size();
for(int i=0;i<4;i++){
if(x+px[i]>=0&&x+px[i]<row&&y+py[i]>=0&&y+py[i]<col&&grid[x+px[i]][y+py[i]]!=0){
int tep=grid[x+px[i]][y+py[i]];
grid[x+px[i]][y+py[i]]=0;
dfs(grid,x+px[i],y+py[i],sum+tep);
grid[x+px[i]][y+py[i]]=tep;
}
}
max_=max(sum,max_);
}
};