//file 汉诺塔问题.cpp
///////////////////////////////////////////////////////////////
// 汉诺塔问题:
//
// 有三根柱子编号为1,2,3,其中1号柱上有若干个大小不等的盘子,
// 大的在下,小的在上(从上到下各盘编号分别为1,2,3,...,n)。
// 现要求将柱1上的盘子全部移到柱3上,在移动的过程中可以借助于2号柱,
// 但一次只能移动一个盘子,且在移动的过程中三根柱子上的盘子始终保持
// 大盘在下,小盘在上的秩序。
//
// 编写完成此项任务的函数,并输出其移动步骤。
///////////////////////////////////////////////////////////////
#include"iostream.h"
void hanoi(int n,int x,int y,int z)
{
if(n==1)
cout<<"将盘"<<n<<"从"<<x<<"柱移到"<<z<<"柱"<<endl;
else{
hanoi(n-1,x,z,y);
cout<<"将盘"<<n<<"从"<<x<<"柱移到"<<z<<"柱"<<endl;
hanoi(n-1,y,x,z);
}
}
void main(void)
{
int n;
cout<<"输入盘数:";
cin>>n;
hanoi(n,1,2,3);
}
//汉偌塔问题中的栈状态及递归执行层次.cpp
#include<iostream>
using namespace std;
void move(char x,int n,char z)
{
cout<<"move No."<<n<<" from "<<x<<" to "<<z<<endl;
}
void hanoi(int n, char x,char y,char z)
/* 1 */{
/* 2 */ if(n==1)
/* 3 */ move(x,1,z);
/* 4 */ else{
/* 5 */ hanoi(n-1,x,z,y);
/* 6 */ move(x,n,z);
/* 7 */ hanoi(n-1,y,x,z);
/* 8 */ }
/* 9 */ }
void main(void)
{
int num;
cout<<"input the number of the plates to move:";
cin>>num;
hanoi(num,'X','Y','Z');
/* 0 */}