-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1-6.用栈来求解汉诺塔问题.cpp
54 lines (49 loc) · 1.4 KB
/
1-6.用栈来求解汉诺塔问题.cpp
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
#include <iostream>
#include <string>
using namespace std;
int process( int num, string left, string mid, string right, string from, string to ) {
if( num == 1 ) {
if( from == "mid" || to == "mid" ) {
cout << "move 1 from " + from + " to " + to << endl;
return 1;
}
else {
cout << "move 1 from " + from + " to mid" << endl;
cout << "move 1 from mid to " + to << endl;
return 2;
}
}
if( from == "mid" || to == "mid" ) {
string another = ( from == "left" || to == "left" ) ? "right" : "left";
int part1 = process( num - 1, left, mid, right, from, another );
int part2 = 1;
cout << "move ";
cout << num;
cout << " from " + from + " to " + to << endl;
int part3 = process( num - 1, left, mid, right, another, to );
return part1 + part2 + part3;
}
else {
int part1 = process( num - 1, left, mid, right, from, to );
int part2 = 1;
cout << "move ";
cout << num;
cout << " from " + from + " to mid" << endl;
int part3 = process( num - 1, left, mid, right, to, from );
int part4 = 1;
cout << "move ";
cout << num;
cout << " from mid to " + to << endl;
int part5 = process( num - 1, left, mid, right, from, to );
return part1 + part2 + part3 + part4 + part5;
}
}
int hanoiProblem1( int num ) {
if( num < 1 ) return 0;
return process( num, "left", "mid", "right", "left", "right" );
}
int main() {
int sum = hanoiProblem1( 2 );
printf( "%d\n", sum );
return 0;
}