Given a gold mine (M) of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially the miner is at first column but can be at any row. He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. Your task is to find out maximum amount of gold which he can collect.
Input : M[][] = {{1, 3, 3},
{2, 1, 4},
{0, 6, 4}};
Output : 12
{(1,0)->(2,1)->(2,2)}
Input: M[][] = {{1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}};
Output : 16
(2,0) -> (1,1) -> (1,2) -> (0,3) OR
(2,0) -> (3,1) -> (2,2) -> (2,3)
What I have tried:
#include<iostream>
#include<vector>
using namespace std;
int func(vector<vector<int>>a,int p,int q,int n,int m,int ans)
{
if(q==m-1)
{
return ans;
}
if(p==0)
{
return max(func(a,p,q+1,n,m,ans+a[p][q+1]),func(a,p+1,q+1,n,m,ans+a[p+1][q+1]));
}
else if(p==n-1)
{
return max(func(a,p,q+1,n,m,ans+a[p][q+1]),func(a,p-1,q+1,n,m,ans+a[p-1][q+1]));
}
else
{
return max(func(a,p,q+1,n,m,ans+a[p][q+1]),
max(func(a,p-1,q+1,n,m,ans+a[p-1][q+1]),func(a,p+1,q+1,n,m,ans+a[p+1][q+1])));
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
vector<vector<int>>a;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int temp;
cin>>temp;
a[i].push_back(temp);
}
}
int p=0;
int q=0;
int ans=0;
cout<<func(a,p,q,n,m,ans+a[0][0])<<endl;
}
return 0;
}