递归实现:把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;
}