有三根杆子A,B,C。A杆上有N个(N>1)穿孔圆盘,盘的尺寸由下到上依次变小。要求按下列规则将所有圆盘移至C杆:
每次只能移动一个圆盘;大盘不能叠在小盘上面。问:如何移?最少要移动多少次?
#include<iostream>
using namespace std;
void hannoi(int n,char from, char buffer, char to)
{
if(n==1)
{
cout<<"Move desk "<<"from "<<from<<" to "<<to<<endl;
}
else
{
hannoi(n-1,from,to,buffer);
cout<<"Move desk "<<"from "<<from<<" to "<<to<<endl;
hannoi(n-1,buffer,from,to);
}
}
int main()
{
int n;
cin>>n;
hannoi(n,'A','B','C');
return 0;
}