c++递归与迭代实现汉诺塔

递归实现:把n个盘子从柱一移到柱三,以柱二为中转的过程:

1.把n-1个盘子从柱一移到柱二,以柱三为中转。

2.把一个盘子从柱一移到柱三

3.把n-1个盘子从柱二移到柱三,以柱一为中转。

假设是三个变量start,end,temp,从start把n个盘子移到end,以temp为中转,即

void move(int n,int start ,int end,int temp)
{
	if(n==1)
	{
		cout<<start<<"->"<<end<<endl;
	}else
	{	
		move(n-1,start,temp,end);
		cout<<start<<"->"<<end<<endl;
		move(n-1,temp,end,start);
	}
}

完整代码与测试:

#include<iostream>
using namespace std;
void move(int n,int start ,int end,int temp)
{
	if(n==1)
	{
		cout<<start<<"->"<<end<<endl;
	}else
	{	
		move(n-1,start,temp,end);
		cout<<start<<"->"<<end<<endl;
		move(n-1,temp,end,start);
	}
}
void main()
{
	move(2,1,3,2);
}

+-

迭代算法:任何递归都能转化为迭代,只要定义一个栈。

#include<iostream>
#include<time.h>

using namespace std;
typedef struct  //stack definition
{
	int n;
	int start;
	int temp;
	int end;
}hanuo;
hanuo han[10000];
int index=0;
void push(hanuo a)
{	
	han[index]=a;
	index++;
} 
hanuo pop()
{
	hanuo temp=han[index-1];
	index--;
	return temp;
}
void move(int n,int x,int y,int z)
{
	hanuo first;
	first.n=n;
	first.start=x;
	first.temp=y;
	first.end=z;
	push(first);
	while(index!=0)
	{
		hanuo abc=pop();
		int num=abc.n;
		int start=abc.start;
		int temp=abc.temp;
		int end=abc.end;
		if(num==1)
		{
			cout<<start<<"->"<<end<<endl;
		}
		else
		{
			hanuo temp1;
			temp1.n=num-1;
			temp1.start=start;
			temp1.temp=end;
			temp1.end=temp;
			push(temp1);
			cout<<start<<"->"<<end<<endl;
			temp1.n=num-1;
			temp1.start=temp;
			temp1.temp=start;
			temp1.end=end;
			push(temp1);
		}
	}

}
void main()
{
	long int time1,time2;
	time1=clock();
	move(10,1,2,3);
	time2=clock();
	double time=(double)(time2-time1)/1000;
	cout<<"spend "<<time<<endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值