懂递归的C程序员进来看看

来源:百度知道 编辑:UC知道 时间:2024/05/26 10:20:18
#include <stdio.h>
int hanoi(int,char,char,char);
int main(int argc, char *argv[])
{
int n;
char a='a',b='b',c='c';
printf("enter the number:\n");
scanf("%d",&n);
hanoi(n,a,b,c);
return 0;
}
int hanoi(int n,char from,char to,char aux)
{
if(n==1)
printf("move disk %d from %c to %c\n",n,from,to);
else
{
hanoi(n-1,from,aux,to);
printf("move disk %d from %c to %c\n",n,from,to);
hanoi(n-1,aux,to,from);
}
}
这个是汉诺塔问题的算法,我想知道总共进行了多少步,也就是说,我想看每一次移动盘子,是第几次移动的,然后了解总步数,比如n==3,那么就是7步,如果是2,就是3步,最好能在每一次移动的前面加个数字,显示步数,谢谢

#include <stdio.h>
int hanoi(int,char,char,char);
int main(int argc, char *argv[])
{
int n,count=0;
char a='a',b='b',c='c';
printf("enter the number:\n");
scanf("%d",&n);
hanoi(n,a,b,c,count);
return 0;
}
int hanoi(int n,char from,char to,char aux,count)
{
count++//计数器加1
if(n==1)
{
printf("%d",count);//输出计数器数
printf("move disk %d from %c to %c\n",n,from,to);
}
else
{
hanoi(n-1,from,aux,to,count);
printf("%d",count);//输出计数器数
printf("move disk %d from %c to %c\n",n,from,to);
hanoi(n-1,aux,to,from,count);
}
}

#include<stdio.h>

void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle);

int i=0;

int main()
{
unsigned n;
printf("please enter the number of disc