版权声明:转载请附上原文链接哟! https://blog.csdn.net/weixin_44170305/article/details/90173403
不恋尘世浮华,不写红尘纷扰,不叹世道苍凉,不惹情思哀怨,闲看花开,静待花落,冷暖自知,干净如始。
题目描述
汉诺塔(又称河内塔)问题是印度的一个古老的传说。开天辟地的神勃拉玛在一个庙里留下了三根金刚石的棒A、B和C,A上面套着n个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去,庙里的众僧不倦地把它们一个个地从A棒搬到C棒上,规定可利用中间的一根B棒作为帮助,但每次只能搬一个,而且大的不能放在小的上面。僧侣们搬得汗流满面,可惜当n很大时这辈子恐怕就很搬了 聪明的你还有计算机帮你完成,你能写一个程序帮助僧侣们完成这辈子的夙愿吗?
输入
输入金片的个数n。这里的n<=10。
输出
输出搬动金片的全过程。格式见样例。
样例输入
copy
2
样例输出
Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C
提示
可以用递归算法实现。
#include<stdio.h>
void hannuo(int m, char ch1, char ch2, char ch3);
int main()
{
int n;
char ch1,ch2,ch3;
ch1='A';
ch2='B';
ch3='C';
scanf("%d",&n);
hannuo(n,ch1,ch2,ch3);
return 0;
}
void hannuo(int n, char ch1, char ch2, char ch3)
{
if(n==1)
{
printf("Move disk %d from %c to %c\n",n,ch1,ch3);
}
else
{
hannuo(n-1,ch1,ch3,ch2);
printf("Move disk %d from %c to %c\n",n,ch1,ch3);
hannuo(n-1,ch2,ch1,ch3);
}
}