Skip to content

Create 1219. Path with Maximum Gold #478

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions 1219. Path with Maximum Gold
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
public:
vector<vector<int>> next = {{0,1},{0,-1},{1,0},{-1,0}};
int getMaximumGold(vector<vector<int>>& g) {
int res =0,n=g.size(),m=g[0].size();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
res = max(res, backTrack(g,i,j,n,m));
}
}
return res;
}

int backTrack(vector<vector<int>>& g, int r, int c, int n, int m) {
if(!isValid(r, c, n, m) || g[r][c]==0) return 0;
int currVal = g[r][c];
g[r][c]=0;
int res = currVal;
int nextRes = 0;
for(int i=0;i<4;i++) {
int nextR = r + next[i][0];
int nextC = c + next[i][1];
nextRes = max(backTrack(g,nextR, nextC,n,m), nextRes);
}
g[r][c]=currVal;
return res + nextRes;
}

bool isValid(int r, int c, int n, int m) {
bool res = (r>=0 && c>=0 && r<n && c<m);
return res;
}
};
Loading