递归实现:
#include<iostream>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<cstdio>
#include<string>
#include<stack>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
void Hanoi(int n,char a,char b,char c)
{
if(n==1){
cout<<a<<" -> "<<c<<endl;
}
else{
Hanoi(n-1,a,c,b);
Hanoi(1,a,b,c);
Hanoi(n-1,b,a,c);
}
return ;
}
int main(void)
{
int n;
cin>>n;
Hanoi(n,'a','b','c');
return 0;
}
非递归实现
#include<iostream>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<cstdio>
#include<string>
#include<stack>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
struct node
{
int n;
char a,b,c;
};
void Hanoi(int n)
{
node p,q;
stack<node> st;
p.n=n,p.a='a',p.b='b',p.c='c';
st.push(p);
while(!st.empty()){
p = st.top();
st.pop();
if(p.n==1) printf("%c -> %c\n",p.a,p.c);
else{
q.n = p.n-1;
q.a = p.b,q.b = p.a,q.c = p.c;
st.push(q);
q.n = 1;
q.a = p.a,q.b = p.b,q.c = p.c;
st.push(q);
q.n = p.n-1;
q.a = p.a,q.b = p.c,q.c = p.b;
st.push(q);
}
}
}
int main(void)
{
int n;
scanf("%d",&n);
Hanoi(n);
return 0;
}