遞歸實現:把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;
}