汉塔问题
#include <iostream>
using namespace std;
#define PUTOUT(n,x,z)\
cout << n << " : " << x << " -> " << z << endl;
void hanoi(int n,char x,char y,char z);
int main()
{
char x = 'x',y = 'y',z = 'z';
hanoi(5,x,y,z);
return 0;
}
void hanoi(int n,char x,char y,char z)
{
if(n == 1)
{
PUTOUT(n,x,z);
}
else
{
hanoi(n - 1,x,z,y);
PUTOUT(n,x,z);
hanoi(n - 1,y,x,z);
}
}
//////////////////// 2 ///////////////////////////////////////////
#include <stdio.h>
递归汉诺塔程序
参数定义:n为移动的盘子数,from指开始所在盘,tmp为中间盘,to为目标盘
void haoii(int n,int from,int tmp,int to)
{
if (n==0) return;
//将n-1个盘子以目标盘为中介,从开始盘递到中间盘
haoii(n-1,from,to,tmp);
/*将最后一个盘子移到目标盘*/
printf("Move %d from %d to %d\n",n,from,to);
//将中间盘上的n-1个盘子移到目标盘
haoii(n-1,tmp,from,to);
}
main()
{
haoii(7,1,2,3);
getchar();
return 0;
}

浙公网安备 33010602011771号