/************************************************************************
功能:解决汉诺塔问题
说明:递归算法解
作者:nicehuai
日期:2015/2/2
*************************************************************************/
#include<iostream>
#include<cstdio>
using namespace std;
void hannoi(int n,char A,char B,char C);
void move(int n,char A,char B);
long long count ;
int main()
{
int n;
count = 1;
cin>>n;
hannoi(n,'A','B','C');
return 0;
}
void hannoi(int n,char A,char B,char C) //递归求汉诺塔问题
{
if(n == 1)
move(1,A,C);
else
{
hannoi(n-1,A,C,B);
move(n,A,C);
hannoi(n-1,B,A,C);
}
}
void move(int n,char A,char B) //每步移动的提示
{
//printf("move %d from %c to %c\n",n,'A','B');
cout<<"step:"<<count++<<" move "<<n<<" from "<<A<<" to "<<B<<endl;
}
用递归解决汉诺塔问题
最新推荐文章于 2024-02-02 10:30:19 发布