I was implementing maxPathSum function using recursion and I didn't know what happens when using two calls in the function .i know then that is called binary recursion and know how to think about it from this reply on that question Understanding double recursion
but when I write the code it didn't give me the right answer [Note that] the only direction needed is right and down
#include <iostream>
#include<algorithm>
using namespace std;
const int MAX=3;
int grid[MAX][MAX]={
{5,1,2},
{6,4,8},
{1,8,9}
};
bool valid(int r, int c);//check not get out grid
int maxPathSum(int r,int c);
int main()
{
int sum=0;
for(int i=0;i<MAX;i++)
sum += maxPathSum(i,i);
cout<<"the sum of the longest path is: "<<sum;
}
int maxPathSum(int r,int c){
if(!valid(r,c))
return 1;
//Reach the last element in the last right down
if(r == MAX-1 && c == MAX-1)
return grid[r][c];
int path1=maxPathSum(r,c+1);//Right
int path2=maxPathSum(r+1,c);//down
return grid[r][c]+max(path1,path2);
}
bool valid(int r, int c){
if(r > MAX-1)
return false;
if(c > MAX-1)
return false;
return true;
}
when I call the function without loop in main sometimes it give me the right answer
like that with low matrix length
const int MAX=2;
int grid[MAX][MAX]={
{5,2},
{1,8}
};
maxPathSum(0,0);