汉诺塔问题求解

要求:碟子的个数为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);
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值