汉诺塔问题(递归算法)

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

效果:

《汉诺塔问题(递归算法)》

    原文作者:递归算法
    原文地址: https://blog.csdn.net/bingdianlanxin/article/details/42364499
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞