/*
*Copyright (c) 2015 烟台大学计算机与控制工程学院
*All right reserved.
*文件名称:hanoi.cpp
//方法二
*Copyright (c) 2015 烟台大学计算机与控制工程学院
*All right reserved.
*文件名称:hanoi.cpp
*writer:罗海员
*date:2015年9月5日
*版本:V1.0.1
*
*问题描述:经典汉诺塔,A.B.C三个柱子,借助于B,将A上边的盘子,依次加到C柱子上。
*输入描述:n和m,分别为柱子数和盘子数,即为将m个盘子在n个柱子上变换。
*程序输出:变换的过程(包括具体的盘子和柱子)
*/
//方法一
#include<iostream>
using namespace std;
int main()
{
void hanoi(int n,char one,char two,char three);
int m;
cin>>m;
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three)
{
if(n==1)
{
cout<<"Move disk 1 from"<<" "<<one<<" "<<"to"<<" "<<three<<endl;
}
else
{
hanoi(n-1,one,three,two);
cout<<"Move disk"<<" "<<n<<" "<<"from"<<" "<<one<<" "<<"to"<<" "<<three<<endl;
hanoi(n-1,two,one,three);
}
}
//方法二
<span style="font-size:14px;">#include<iostream>
using namespace std;
int main()
{
void hanoi(int n,char one,char two,char three);
int m;
cin>>m;
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three)
{
void move(char x,char y);
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move(char x,char y)
{
int i,n;
cin>>n;
for(i=1;i<=n;i++)
cout<<"Move disk"<<" "<<i<<" "<<"from"<<" "<<x<<" "<<"to"<<" "<<y<<endl;
}</span>