Home > Net >  how to count the number of paths I can take given a coordinates (x,y) using one step/two steps down
how to count the number of paths I can take given a coordinates (x,y) using one step/two steps down

Time:12-11

I need help writing a recursive code for my question (the recursion ends when both of them x and y are zero),for exapmle the input (2,1)to get to (0,0), the expected output should be 5 :[enter image description here][1]

this is what I have written so far but its not correct ..its maybe correct for one step down /left but not also two steps :

#include<stdio.h>
int numOfPaths(int x,int y);
int main()
{
    int x=0,y=0,sum=0;
    printf("Enter the initial coordinates of Alice and her friends:");
    if(scanf("%d%d", &x, &y)!=2)
    {
        printf("invalid input/n");
        return 0;
    }
   
    sum=numOfPaths(x,y);
    printf("The number of paths Alice and her friends have is:%d",sum);
    return 0;
}
/*the change that I made on the function */
int numOfPaths(int x, int y)
{
    if(x==0 && y==0)
        return 1;
    else
        return(numOfPaths(x-1,y)   numOfPaths(x,y-1)  numOfPaths(x,y-2)   numOfPaths(x-2,y));
}


  [1]: https://i.stack.imgur.com/SDxBF.png

CodePudding user response:

Best bet I can have with the description of your problem :

#include <stdio.h>

int numOfPaths(int x, int y)
{   
    // If you're arrived
    if (x == 0 && y == 0) {
        return 1;
    }
    // If you're out of bound
    if (x < 0 || y < 0) {
        return (0);
    }

    // Trying the 4 possibility
    return(numOfPaths(x - 1, y)   numOfPaths(x, y - 1)   numOfPaths(x - 2, y)   numOfPaths(x, y - 2));
}

int main(void)
{
    printf("The number of paths Alice and her friends have is : %d", numOfPaths(2, 1));
    
    return 0;
}
  • Related