汉诺塔问题(递归算法)

1.汉诺塔问题

约19世纪末,在欧洲的商店中出售一种智力玩具,在一块铜板上有三根杆,最左边的杆上自上而下、由小到大顺序串着由64个圆盘构成的塔,游戏的目的是将最左边杆上的盘全部移到最右边的杆上,条件是一次仅能移动一个盘,且不允许大盘放在小盘上面。


分析:

首先考虑a杆最下面的盘子,于是任务就变成了:

1.将a杆上面的63个盘子移到b杆上

2.将a杆上剩下的盘子移到c杆上

3.将b杆上的全部盘子移到c杆上

将这个过程继续下去,就是要先完成移动63个盘子、62个盘子、61个盘子......的工作。

为了更清楚地描述算法,可以定义一个函数movedisc(n,a,b,c)。该函数的功能是:将N个盘子从A杆上借助C杆移动到B杆上。

这样移动N个盘子的工作就可以按以下过程进行:

1.movedisc(n-1,a,c,b)

2.将一个盘子从a移动到b上

3.movedisc(n-1,c,b,a)

重复以上过程,直到将全部盘子移动到位时为止。


源码:

#include <iostream.h>

int g_count = 0;

void move(char x,char y)
{
	g_count++;
	cout<<x<<"-->"<<y<<endl;
}

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);
	}
}

void main()
{
	int m;
	g_count = 0;
	cout<<"input the number of diskes:"<<endl;
	cin>>m;
	cout<<"the step to moving "<<m<<" diskes:"<<endl;
	hanoi(m,'A','B','C');

	cout<<"move times: "<<g_count<<endl;
}

效果:
当只有1个盘子时,直接移动:


当有2个盘子时:


当有3个盘子时:


当有4个盘子时:



2.利用递归方法求阶乘

源码:

#include <iostream.h>

float fac(int n)
{
	float f;
	if(n<0) cout<<"n<0,date error"<<endl;
	else if( n==0 || n==1 ) f=1;
	else f=fac(n-1)*n;
	return f;
}

void main()
{
	int n;
	float y;
	cout<<"input an integer number :"<<endl;
	cin>>n;
	y=fac(n);
	cout<<n<<"!="<<y<<endl;
}
效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值