汉诺塔的递归解法

来源:互联网 发布:取名软件哪个好 编辑:程序博客网 时间:2024/04/28 22:11

 #include<iostream>
using std::cout;
using std::cin;
using std::endl;
/*此问题只能用递归方法来解决。设A柱上最初的盘子总数为n,问题的解法为:如果n=1,则将这一个盘子直接从
A柱移到C柱上;否则,执行以下三步:
(1)、用C柱做过渡,将A柱上的n-1个盘子移到B柱上;
(2)、将A柱上最后一个盘子直接移到C柱上;
(3)、用A柱做过渡,将B柱上的n-1个盘子移到C柱上。
*/
void move(char one,char another)
{
 cout<<one<<"移动到"<<another<<endl;
}
void hanoi(int n,char no1,char no2,char no3)
{
 if(n==1) move(no1,no3);
 else
 {
  hanoi(n-1,no1,no3,no2);
  move(no1,no3);
  hanoi(n-1,no2,no1,no3);
 }
}
int main ()
{
 void hanoi(int n,char no1,char no2,char no3);
 int m;
 cout<<"请输入A柱上的金盘子总数:";
 cin>>m;
 cout<<"当有"<<m<<"个金盘子时,移动步骤依次为:"<<endl;
 hanoi(m,'A','B','C');
 return 0;
}

原创粉丝点击