c语言:Hanoi(汉诺)塔问题,求移动盘子的步骤

Hanoi(汉诺)塔问题。古代有一个焚塔,塔内有3个座A,B,C,开始时A座上有64个盘子,盘子大小不等,大的在上,小的在下,有一个老和尚想把这64个盘子从A座移到C座,但规定每次只允许移到一个盘,且在移动过程中在3个座上都始终保持大盘在下,小盘在上,在移动过程中可以利用B座。输出移动盘子的步骤。

解:由于64个盘子移动步骤太多,本程序以3个盘子为例进行输出

程序:

 

#include<stdio.h>


void hanoi(int n,char one,char two,char three)

{

void move(char x, char y);

if (n ==1)

{

move(one,three);

}

else 

{

hanoi(n-1,one,three,two);

move(one, three);

hanoi(n - 1, two, one, three);

}

}


void move(char x, char y)

{

printf("%c-->%c\n", x, y);

}


int main()

{

int n;

printf("input the number of diskes:");

scanf("%d", &n);

printf("The step to move %d diskes:\n",n);

hanoi(n, 'A', 'B', 'C');

return 0;

}

结果:

input the number of diskes:3

The step to move 3 diskes:

A-->C

A-->B

C-->B

A-->C

B-->A

B-->C

A-->C

请按任意键继续. . .


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1746843

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值