【算法】汉诺塔问题 Hanoi Tower
程序员文章站
2024-03-17 08:44:16
...
题目内容
汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
输入盘子的数量n,求多少步能搬完。
经验值:最少步数:2^n - 1
样例输入
3
样例输出
7
//C语言求移动次数的递归函数
include<stdio.h>
int h(int m)
{
int s;
if(m==1) // 确定初始条件
s=1;
else
s=2*h(m-1)+1;
return s;
}
int main()
{
int n;
scanf("%d",&n);
printf("%ld",h(n));
}
提示“请输入盘子数:”,输入盘子的数量n,打印移动过程,并输出“总共移动了n次”。
//C++
#include<iostream>
using namespace std;
int s=0;
void move(char m,char n)
{
cout<<m<<" → "<<n<<endl;
s++;
}
void hanoi(int n,char a,char b,char c)
{
if(n==1)
{
move(a,c);
}
else
{
hanoi(n-1,a,c,b);//借助c将n-1个盘子从a移动到b
move(a,c);
hanoi(n-1,b,a,c);//借助a将n-1个盘子从b移动到c
}
}
int main()
{
int n;
cout<<"请输入盘子数:";
cin>>n;
cout<<"移动"<<n<<"个盘子的过程:"<<endl;
hanoi(n,'A','B','C') ;
cout<<"总共移动了"<<s<<"次";
return 0;
}
using namespace std;
int hannuota(int n, string a, string b, string c)
{
if (n == 1)
{
//只有一个盘子的情况下直接将第一个塔上的盘子移动到第三个塔
printf("%d from %s to %s\n", n,a.c_str(), c.c_str());
}
else {
//1.先将第一个塔的n-1个盘子全部通过第三个塔移动到第二个塔上
hannuota(n - 1, a, c, b);
//2.再将剩下的一个盘子移动到第三个塔上
printf("%d from %s to %s\n",n, a.c_str(), c.c_str());
//3.最后将第二个塔上的盘子通过第一个塔移动到第三个塔上
hannuota(n - 1, b, a, c);
}
return 1;
}
int main(int argc, const char * argv[]) {
int n;
scanf("%d", &n);
hannuota(n, "A", "B", "C");
system("pause");
return 0;
}