C++:汉诺塔问题

16 篇文章 1 订阅
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值