69,371
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
int i=0;
void hanoi(int n,char A,char B,char C){
if(n==1){
printf("Move disk %d from %c to %c.\n",n,A,C);
i++;
}
else{
hanoi(n-1,A,C,B);
printf("Move disk %d from %c to %c.\n",n,A,C);
i++;
hanoi(n-1,B,A,C);
}
}
int main(){
int n;
printf("请输入n阶汉诺塔:\n");
while(scanf("%d",&n)==1){
hanoi(n,'A','B','C');
printf("共%d步.\n",i);
i=0;
printf("请输入n阶汉诺塔:\n");
}
system("pause");
return 0;
}
viod hanoi(int n,char A,char B,char C)
void hanoi(int n,char A,char B,char C){
if(n==1){ //如果A上面只有一个盘子,直接从A移动到C上。
printf("Move disk %d from %c to %c.\n",n,A,C);
i++;
}
else{
hanoi(n-1,A,C,B); //否则就是上面第一条 1、把A上面的n-1个盘子移到B上去
printf("Move disk %d from %c to %c.\n",n,A,C); //然后第二条:2、把A上面剩下的1个盘子移到C上去
i++;
hanoi(n-1,B,A,C); //再然后第三条:3、把B上面的n-1个盘子移到C上去。
}
}
是不是这种情况?