Hanoi(汉诺)塔问题:
古代有一个梵塔,塔内有3个座,A,B,C。开始时A座上有64个盘子,盘子大小不等,大的在下,小的在上,一个老和尚想把这64个盘子从A移到C座,但规定每次只能移动一个盘,且在移动过程中在3个座上都始终保持大盘在下,小盘在上,在移动过程中可以利用B座,编程序输出盘子移动步骤。
分析:
(1)将A座上的n-1个盘借助C座先移到B座上;
(2)把A座上的剩下一个盘移到C座上;
(3)将n-1个盘从B座借助于A座移到C座上;
代码1:
//汉诺塔
#include<stdio.h>
void hanoi(int n,char one,char two,char three);
void move(char x,char y);
int main(){
printf("input the number of diskes:");
int m;
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three){
//将n个盘从one座借助two座,移到three座
//one起始 two中转 three目标
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);
}
结果:
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
代码2:
//汉诺塔
#include<stdio.h>
void hanoi(int n,char one,char two,char three);
int main(){
printf("input the number of diskes:");
int m;
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three){
//将n个盘从one座借助two座,移到three座
//one起始 two中转 three目标
if(n==1){
printf("%c-->%c\n",one,three);
}else{
hanoi(n-1,one,three,two);
printf("%c-->%c\n",one,three);
hanoi(n-1,two,one,three);
}
}
结果:
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