I wrote the following function to find out the number of paths we can reach from the start cell (0,0)
to the destination cell (n,n)
. I cannot, for the life of me, figure out why this is infinite recursion.
Code is as follows:
#include <iostream>
using namespace std;
int numOfPathsToDestUtil(int start, int end, int noOfPaths, int n) {
cout<<"Start: "<<start<<" and end: "<<end<<"and n: "<<n<<"\n";
if(start==end && start==n)
return noOfPaths;
if(end<start)
return 0;
numOfPathsToDestUtil(start+1, end, noOfPaths+1,n) + numOfPathsToDestUtil(start, end+1, noOfPaths+1,n);
}
int numOfPathsToDest( int n )
{
cout<<"n is: "<<n<<"\n";
return numOfPathsToDestUtil(0,0,0,n);
}
int main() {
int ans = numOfPathsToDest(4);
cout<<ans;
return 0;
}
Note: I am not requesting help with the code (saying so, because conditions like end<start
are implementation-specific. Request you to let me understand why this recursion does not stop:
n is: 4
Start: 0 and end: 0and n: 4
Start: 1 and end: 0and n: 4
Start: 0 and end: 1and n: 4
Start: 1 and end: 1and n: 4
Start: 2 and end: 1and n: 4
Start: 1 and end: 2and n: 4
Start: 2 and end: 2and n: 4
Start: 3 and end: 2and n: 4
Start: 2 and end: 3and n: 4
Start: 3 and end: 3and n: 4
Start: 4 and end: 3and n: 4
Start: 3 and end: 4and n: 4
Start: 4 and end: 4and n: 4 --> I expect it to stop here as start=end and start=n
Start: 3 and end: 5and n: 4
Start: 4 and end: 5and n: 4
Start: 5 and end: 5and n: 4
Start: 6 and end: 5and n: 4
Start: 5 and end: 6and n: 4
Start: 6 and end: 6and n: 4
Thank you so much!