汉诺塔问题 hanoi(递归)

//汉诺塔问题-hanoi 
//现有ABC三个柱子,A中有n个盘(上小下大),移动到c上,要求全程上小下大
//算法:递归,把1~n-1个盘当作一个整体 


#include


//函数声明


//函数功能:把n个盘 从A 借助B,移到C 
hanoi(int n,char x,char y,char z);
//函数功能:把一个盘子x->y 
move(char x,char y);
int main()
{   //tip
    printf("welcome...\nthis is the problem named the tower of hanoi...\n");
    int n;
    char ans='y';
    while(ans=='y'||ans=='Y')
 {   
printf("how many dish of this tower of hanoi problem,n=");
scanf("%d",&n);
getchar();
//tip
printf("the way of removing is >>>\n");
hanoi(n,'A','B','C');
A1: printf("do you wanna continue...ans=");
scanf("%c",&ans);
getchar();
if(ans=='n'||ans=='N') break;
if(ans!='n'&&ans!='N'&&ans!='y'&&ans!='Y')
{
printf("input error!again!\n");
goto A1;
}
}
getchar();
return 0;
 }
 
 //函数原型
 move(char x,char y)//move()放在hanoi后没毛病,声明也放hanoi()后也·没毛病 
 {
  printf("%c->%c\n",x,y);
 }
 
 hanoi(int n,char a,char b,char c)
 {
    if(n==1) move(a,c);
else{
hanoi(n-1,a,c,b);
move(a,c);
hanoi(n-1,b,a,c);
} 
 }
 
 //goto A1
 
 
 
 

 
 
  

 

你可能感兴趣的:(001语言-C)