练习 03-03-03 汉诺(Hanoi)塔问题
问题描述:
古代有一个梵塔,塔内有三个座A,B,C,开始的时候,A座上有64个盘子,盘子大小不等,大的在下面,小的在上面。有一个老和尚想要把64个盘子从A座位移动到C座位上,但是规定每次只允许移动一个盘子,且在移动的过程中,在三个座位上都始终保持大盘在下,小盘在上。在移动的过程中可以利用B座。要求编写程序输出移动盘子的步骤。
分析:将n个盘子从A座移动到C座上可以分解为以下三个步骤:
(1)将A上n-1个盘借助C移动到B座位上,
(2)将A座位上的最后一个盘子移动到C座位上;
(3)将n-1个盘子从B座位上借助A座位移动到C座位上。
以上的三个步骤可以分解为两类操作:
- 将n-1个盘子从一个座位移动到另外一个座位上(n>1)
- 将1个盘子从一个座位上移动到另外一个座位上。
下面以3个盘子为例,有以下输出:
Input the numbers of diskes:3
The steps to move:
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
--------------------------------
Process exited after 1.513 seconds with return value 0
请按任意键继续. . .
代码如下:
#include<stdio.h>
int main()
{
void hanoi(int n,char one,char two,char three);
printf("Input the number of discks = ");
int m;
scanf("%d",&m);
printf("%d\n",m);
printf("The steps to move:\n");
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three) //hanoi函数是将one中的盘借助two移动到three
{
void move(char x,char y);
if(n==1){
move(one,three);
}else{
hanoi(n-1,one,three,two); //需要先将one中的前n-1个盘子借助three移动到two
move(one,three); //最后移动one中剩下那个盘子
hanoi(n-1,two,one,three); //将two上的n-1个盘子,按照之前的操作移动
}
}
void move(char x,char y)
{
printf("%c->%c\n",x,y);
}