Skip to content

Commit d924cf4

Browse files
authored
Create path-with-maximum-gold.cpp
1 parent 1f25892 commit d924cf4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

C++/path-with-maximum-gold.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(m^2 * n^2)
2+
// Space: O(m * n)
3+
4+
class Solution {
5+
public:
6+
int getMaximumGold(vector<vector<int>>& grid) {
7+
int result = 0;
8+
for (int i = 0; i < grid.size(); ++i) {
9+
for (int j = 0; j < grid[0].size(); ++j) {
10+
if (grid[i][j]) {
11+
result = max(result, backtracking(&grid, i, j));
12+
}
13+
}
14+
}
15+
return result;
16+
}
17+
18+
private:
19+
int backtracking(vector<vector<int>> *grid, int i, int j) {
20+
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
21+
{0, -1}, {-1, 0}};
22+
int result = 0;
23+
(*grid)[i][j] *= -1;
24+
for (const auto& [dx, dy] : directions) {
25+
int ni = i + dx;
26+
int nj = j + dy;
27+
if (!(0 <= ni && ni < grid->size() &&
28+
0 <= nj && nj < (*grid)[0].size() &&
29+
(*grid)[ni][nj] > 0)) {
30+
continue;
31+
}
32+
result = max(result, backtracking(grid, ni, nj));
33+
}
34+
(*grid)[i][j] *= -1;
35+
return (*grid)[i][j] + result;
36+
}
37+
};

0 commit comments

Comments
 (0)