您的位置:首页 > 其它

汉诺塔问题求解

2011-03-08 13:21 357 查看
要求:碟子的个数为n,把它从x通过y全部搬到z中。

 

思路:若n==1,直接从x搬到z;

         否则,先借助z把n-1个从x搬到y,在把第n个从x中搬到z中,再借助x,把y中n-1个搬到z中

 

测试代码如下:

#include<stdio.h>
void hanoi(unsigned char  n,char x,char y,char z);
int main()
{
 unsigned int n;
 char x='x',y='y',z='z';
 printf("Please input the number of the disks/n");
 scanf("%d",&n);
 if(n==0)
 {
  printf("Please input a positive number/n");
  scanf("%d",&n);
 }
 hanoi(n,x,y,z);
 return 0;
}
 
void hanoi(unsigned int  n,char x,char y,char z)
{
 if(n==1)
  printf("Move %d from %c  to  %c/n",n,x,z);
 else
 {
  hanoi(n-1,x,z,y);
  printf("Move %d from %c  to  %c/n",n,x,z);
  hanoi(n-1,y,x,z);
 }
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  input 测试 c