我需要幫助為我的問題撰寫遞回代碼(當 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
uj5u.com熱心網友回復:
我可以對您的問題進行描述的最佳選擇:
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378934.html
