汉诺塔问题

好家伙,经典永不过时!

他人的

others

B站视频


递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;

void hanoi(char A,char B,char C,int n)
{
if(n)
{
hanoi(A,C,B,n-1);
cout<<A<<" -> "<<C<<endl;
hanoi(B,A,C,n-1);
}
}

int main()
{
int n;
char a='a',b='b',c='c';
cin>>n;
hanoi(a,b,c,n);
return 0;
}

非递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<iostream>
#include<stack>
using namespace std;

char s[4]={'0','a','b','c'};
stack<int> a[4];

void move(int now,int next)
{
a[next].push(a[now].top());
//printf("%d from %c to %c",a[now].top(),s[now],s[next]);
cout<<s[now]<<" -> "<<s[next]<<endl;
a[now].pop();
}

int main()
{
int n,count=0;
cin>>n;
for(int i=0;i<n;++i)
a[1].push(n-i);
if(n%2)
{
s[2]='c';
s[3]='b';
}
while(1)
{
int next;
for(int i=1;i<=3;++i)
{
if(!a[i].empty()&&a[i].top()==1)
{
if(i==3) next=1;
else next=i+1;
move(i,next);
break;
}
}

if(a[2].size()==n||a[3].size()==n)
break;

int other1,other2;
switch(next)
{
case 1:{
other1=2;other2=3;
break;
}
case 2:{
other1=3;other2=1;
break;
}
case 3:{
other1=1;other2=2;
break;
}
}
if(a[other1].empty())
move(other2,other1);
else if(a[other2].empty())
move(other1,other2);
else
{
if(a[other1].top()<a[other2].top())
move(other1,other2);
else
move(other2,other1);
}
}
return 0;
}

时间复杂度:O(2n)O(2^n)


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!