汉诺塔
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
汉诺塔(又称河内塔)问题是印度的一个古老的传说。
开天辟地的神勃拉玛在一个庙里留下了三根金刚石的棒A、B和C,A上面套着n个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去,庙里的众僧不倦地把它们一个个地从A棒搬到C棒上,规定可利用中间的一根B棒作为帮助,但每次只能搬一个,而且大的不能放在小的上面。
僧侣们搬得汗流满面,可惜当n很大时这辈子恐怕就很搬完了。
聪明的你还有计算机帮你完成,你能写一个程序帮助僧侣们完成这辈子的夙愿吗?
Input
输入金片的个数n。这里的n<=10。
Output
输出搬动金片的全过程。格式见样例。
Example Input
2
Example Output
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Hint
可以用递归算法实现。
Author
#include <bits/stdc++.h>usingnamespacestd;
void move (int n,char a,char b,char c)
{
if(n==1)///1片叶子直接输出
{
cout<<"Move disk "<<n<<" from "<<a<<" to "<<c<<endl;
}
else
{
move(n-1,a,c,b);///把A的叶子移到B上cout<<"Move disk "<<n<<" from "<<a<<" to "<<c<<endl;
move(n-1,b,a,c);///把B的叶子移到C上
}
}
int main()
{
int n;///金片的片数while(cin>>n)
{
move(n,'A','B','C');/// (叶片的数量,叶子的开始的柱子,叶子的中间柱子,目标柱子)
}
return0;
}