c语言程序设计电子图书 汉诺塔,用C写的汉诺塔(hanoi)程序

用C写的汉诺塔(hanoi)程序

分类:计算机等级

|

更新时间:2016-07-07|

来源:转载

#include

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

int i=0;

void main()

{

unsigned n;

printf("请输入盘子的数量:");

scanf("%d",&n); /*输入N值*/

printf("\t柱子:\t a\t b\t c\n");

movedisc(n,'a','c','b'); /*从A上借助B将N个盘子移动到C上*/

printf("\t 共计: %d步\n",i);

}

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

{

if(n>0)

{

movedisc(n-1,fromneedle,usingneedle,toneedle);

/*从fromneedle上借助toneedle将N-1个盘子移动到usingneedle上*/

++i;

switch(fromneedle) /*将fromneedle 上的一个盘子移到toneedle上*/

{

case 'a': switch(toneedle)

{

case 'b': printf("\t[%d]:\t%2d———>%2d\n",i,n,n);

break;

case 'c': printf("\t[%d]:\t%2d———————>%2d\n",i,n,n);

break;

}

break;

case 'b': switch(toneedle)

{

case 'a': printf("\t[%d]:\t%2d

break;

case 'c': printf("\t[%d]:\t\t%2d———>%2d\n",i,n,n);

break;

}

break;

case 'c': switch(toneedle)

{

case 'a': printf("\t[%d]:\t%2d

break;

case 'b': printf("\t[%d]:\t\t%2d

break;

}

break;

}

movedisc(n-1,usingneedle,toneedle,fromneedle);

/*从usingneedle上借助fromneedle将N-1个盘子移动到toneedle上*/

}

}

运行后:

请输入盘子的数量:3

柱子: a b c

[1]: 1———————>1

[2]: 2———> 2

[3]: 1

[4]: 3———————>3

[5]: 1

[6]: 2———>2

[7]: 1———————> 1

共计: 7步

Press any key to continue...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值