[LeetCode] Path with Maximum Gold

1219. Path with Maximum Gold

In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

Return the maximum amount of gold you can collect under the conditions:

  • Every time you are located in a cell you will collect all the gold in that cell.
  • From your position, you can walk one step to the left, right, up, or down.
    You can’t visit the same cell more than once.
  • Never visit a cell with 0 gold.
  • You can start and stop collecting gold from any position in the grid that has some gold.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int dfs(vector<vector<int>>& grid, int y, int x) {
if(0 > y or 0 > x or y >= grid.size() or x >= grid[y].size() or grid[y][x] == 0)
return 0;
int cell = grid[y][x];
grid[y][x] = 0;
int res = cell;
res = max(res, dfs(grid,y+1,x) + cell);
res = max(res, dfs(grid,y-1,x) + cell);
res = max(res, dfs(grid,y,x+1) + cell);
res = max(res, dfs(grid,y,x-1) + cell);
grid[y][x] = cell;
return res;
}
public:
int getMaximumGold(vector<vector<int>>& grid) {
int res = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[i].size(); j++)
res = max(res, dfs(grid,i,j));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/path-with-maximum-gold/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.