题解
Medium | Backtracking
class Solution {
public:
int getMaximumGold(vector<vector<int>>& grid) {
int ret = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
helper(grid, i, j, 0, ret);
}
}
return ret;
}
void helper(vector<vector<int>>& grid, int x, int y, int curr,int& max_gold) {
if(x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == 0) {
return;
}
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
if(curr+grid[x][y] > max_gold) {
max_gold = curr + grid[x][y];
}
int temp = grid[x][y];
curr = curr + grid[x][y];
grid[x][y] = 0;
for(auto& dir : dirs) {
int next_x = x + dir[0];
int next_y = y + dir[1];
helper(grid, next_x, next_y, curr, max_gold);
}
grid[x][y] = temp;
}
};