#include<iostream>
#include<conio.h>
using namespace std;
#define MAX 100
typedef struct
{
int elem[MAX];
int top;
}SeqStack;
SeqStack A;
SeqStack B;
SeqStack C;
int sum;
void show()
{
int i;
cout<<"A上的金片: ";
for(i=0;i<A.top;i++)
{
cout<<A.elem[i]<<" ";
}
cout<<endl;
cout<<"B上的金片: ";
for(i=0;i<B.top;i++)
{
cout<<B.elem[i]<<" ";
}
cout<<endl;
cout<<"C上的金片: ";
for(i=0;i<C.top;i++)
{
cout<<C.elem[i]<<" ";
}
cout<<endl<<endl;
}
void Init(SeqStack &S)
{
S.top=0;
}
void move(int n,SeqStack &X,SeqStack &Z)
{
Z.top++;
Z.elem[Z.top-1]=X.elem[X.top-1];
X.top--;
return ;
}
void hanoi(int n,SeqStack &X,SeqStack &Y,SeqStack &Z)
{
if(n==1)
{
sum++;
move(n,X,Z);
cout<<"第"<<sum<<"次移动:"<<endl;
show();
}
else
{
hanoi(n-1,X,Z,Y);
sum++;
move(n,X,Z);
cout<<"第"<<sum<<"次移动:"<<endl;
show();
hanoi(n-1,Y,X,Z);
}
}
int main ()
{
sum=0;
Init(A);
Init(B);
Init(C);
cout<<"请输入金片的数量(不超过100个)"<<endl;
int a;
cin>>a;
A.top=a;
for(int i=0;i<a;i++)
{
A.elem[i]=a-i;
A.top=a;
}
cout<<"初始状态为下图,按任意键开始自动移动"<<endl;
show();
getch();
hanoi(a,A,B,C);
cout<<"移动完成!共用了"<<sum<<"步!"<<endl;
cin>>a;
return 0;
}
C++:汉诺塔问题
最新推荐文章于 2020-11-21 11:46:35 发布