gpt4 book ai didi

arrays - 计算二维数组中从 arr[0,0] 到 arr[N,M] 的路径数,其中只能向右和向下移动

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:00 28 4
gpt4 key购买 nike

给定一个大小为 [N,M] 的二维数组,计算从“左上角” (arr [0, 0]) 到数组的“右下角”(arr[N - 1, M - 1])。

最佳答案

我们将使用递归解决方案,其中:

1)停止条件会返回:

  • 1,如果我们到达arr[N,M]

  • 0,如果我们超出了数组的“边界”。

2) 递归调用将再次调用该函数,一次是我们向右移动的地方,一次是我们向下移动的地方。

注意:dim1dim2 总是以数组的原始大小 (N,M) 发送。

递归函数的实现将是:

int numOfPathsToEndOfTwoDimMatrix(int x, int y, int dim1, int dim2)
{
if (x == dim1 - 1 && y == dim2 - 1)
{
return 1;
}

if (x > dim1 - 1 || y > dim2 - 1)
{
return 0;
}

return numOfPathsToEndOfTwoDimMatrix(x + 1, y, dim1, dim2) + numOfPathsToEndOfTwoDimMatrix(x, y + 1, dim1, dim2);
}

函数的调用如下:

void main(int argc, char** argv)
{
int n = 3;
int m = 3;
printf("numOfPathsToEndOfTwoDimMatrix(0,0, %d, %d) returned:%d \n", n, m,
numOfPathsToEndOfTwoDimMatrix(0,0, n, m));
}

关于arrays - 计算二维数组中从 arr[0,0] 到 arr[N,M] 的路径数,其中只能向右和向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53088689/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com