problem link : - LeetCode
I have not included the condition to not go for positions having zero but shold only change the answer at max and not cause segmentation fault.
using namespace std;
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
// #include <bits/stdc++.h>
class Solution
{
public:
int travelInmine(int r, int c, vector<vector<int>> &grid)
{
if(c >=grid[0].size() || c < 0){
return 0;
}
if(r >=grid.size() || r < 0){
return 0;
}
int up = travelInmine(r-1,c,grid);
int down = travelInmine(r+1,c,grid);
int left = travelInmine(r,c-1,grid);
int right = travelInmine(r,c+1,grid);
return grid[r][c] + max({up,down,right,left});
}
int getMaximumGold(vector<vector<int>> &grid)
{
int mxm = 0;
for (int i = 0; i < grid.size(); i++)
{
if(grid[i][0] != 0){
mxm = max(mxm, travelInmine(i, 0, grid));
}
}
return mxm;
}
};
int main()
{
// code here
vector<vector<int>> mat{{1, 0, 7},
{2, 0, 6},
{3, 4, 5},
{0, 3, 0},
{9, 0, 20}};
Solution s;
cout << s.getMaximumGold(mat);
return 0;
}