只有一个盘子的时候,直接把盘子从A移到目标盘B;
当A塔上有n个盘子是,先将A塔上编号1至n-1的盘子(共n-1个)移动到C塔上(借助B塔),然后将A塔上最大的n号盘子移动到B塔上,最后将C塔上的n-1个盘子借助A塔移动到B塔上。
#include <iostream>
using namespace std;
int main()
{
int num=0;
void hanio(int n,char A,char B,char C);
cout<<"Please input the number of hanio:"<<endl;
cin>>num;
hanio(num,'A','B','C');
system("pause");
return 0;
}
void hanio(int n,char A,char B,char C)
{
if(n==1)
cout<<"Put "<<n<<" from "<<A<<" to "<<B<<endl;
else
{
hanio(n-1,A,C,B); <span style="font-family: Arial; font-size: 18px; line-height: 26px;">//先将上面的n-1个盘移到C</span>
cout<<"Put "<<n<<" from "<<A<<" to "<<B<<endl; <span style="font-family: Arial; font-size: 18px; line-height: 26px;">//决定目标盘,选择B,则移动第二个盘,最低盘只移1次</span>
hanio(n-1,C,B,A); <span style="font-family: Arial; font-size: 18px; line-height: 26px;">//将剩下的n-1个盘移到目标盘</span>
}
}