gta5火箭狂雷怎么飞:N阶Hanoi问题求解

来源:百度文库 编辑:中科新闻网 时间:2024/05/04 11:29:25
设有三个塔座分别为X,Y ,Z。先有N个直径各不相同的圆盘,且按直径从小到大编号为1,2,3……。开始时都放在X上。现在要按以下规则移动盘子。
1.每次只能移动一个。
2.Y可作为中间柱。
3.移动过程中不能出现大盘压小盘的情况。

求算法,最好是用C或者JAVA语言描述!(C++我已经忘记了)

晕,我给出了C++的程序。你不会不知道改成C语言吧?

算法描述
PROCEDURE Ahanoi(n,x,y,z)
IF n=1 THEN move(x,1,z)
ELSE
{Ahanoi(n-1,x,z,y)
move(x,n,z)
Ahanoi(n-1,y,x,z)
}
RETURN

程序代码
#include <iostream.h>
void move(char x,char y)
{cout<<x<<"-->"<<y<<"\n";}
void hanoi(int n,char one,char two,char three)
{ if(n==1) move(one,three);else{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);}
}
main()
{
int m;
cout<<"Input the number of disks:"<<"\n";
cin>>m;
cout<<"The step to move"<<m<<"disks"<<"\n";
hanoi(m,'A','B','C');
return 0;
}

这个用递归做很简单,给你一个我做过的C++的程序
//Hanoi by yzz
#include<iostream.h>

void move(int,int,int,int);

int main()
{
int n,x=1,y=2,z=3;

cout<<"Enter the number of plates: ";
cin>>n;
move(n,x,y,z);

return 0;
}

void move(int n,int x,int y,int z)
{
if (n==1)
cout<<x<<">"<<z<<"\t";
else
{
move(n-1,x,z,y);
cout<<x<<">"<<z<<"\t";
move(n-1,y,x,z);
}
}