C语言 如何计算给定一个坐标(x,y),使用一步/两步向下或向左到达(0.0)的路径数?

fcg9iug3  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(93)

我需要帮助为我的问题编写递归代码(当x和y都为零时递归结束),例如输入(2,1)到达(0,0),预期输出应为5:[在此输入图像描述][1]
这是我到目前为止所写的,但它不正确。。它可能是正确的一步下/左,但也不是两步:

#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
jq6vz3qz

jq6vz3qz1#

我无意中发现了我的这个老答案,我必须承认,我有点困惑,我给了这样奇怪的代码。
下面是一个更好的版本:

#include <stdio.h>

int CalculateNumberOfPaths(int x, int y)
{
    int numberOfPaths = 0;
    
    // 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 all possible left move (x axis)
    for (int i = 1; i <= x; ++i) {
        numberOfPaths += CalculateNumberOfPaths(x - i, y);
    }

    // Trying all possible down move (y axis)
    for (int j = 1; j <= y; ++j) {
        numberOfPaths += CalculateNumberOfPaths(x, y - j);
    }
    
    return numberOfPaths;
}

int main(void)
{
    printf("The number of paths Alice and her friends have is : %d", CalculateNumberOfPaths(4, 4));
    
    return 0;
}

如果需要限制最大轴移动,只需在for循环中添加&& i <= 2或其他移动限制。

最好的赌注我可以有与描述您的问题:

#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;
}

相关问题