-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTowers of Hanoi.cpp
69 lines (57 loc) · 2.06 KB
/
Towers of Hanoi.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> t[3];
int n;
cout << "Please enter the number of rings to move: ";
cin >> n;
cout << endl;
// The initial value of to depends on whether n is odd or even
int from = 0, candidate = 1, move = 0;
int to;
if(n%2==1)to=1;
else to=2;
// Initialize the towers
for(int i = n + 1; i >= 1; --i)
t[0].push_back(i);
t[1].push_back(n+1);
t[2].push_back(n+1);
while (t[1].size() < n+1) { // while t[1] does not contain all of the rings
cout << "Move #" << ++move << ": Transfer ring " << candidate << " from tower " << char(from+'A') << " to tower " << char(to+'A') << "\n";
// Move the ring from the "from tower" to the "to tower" (first copy it, then delete it from the "from tower")
t[to].push_back(t[from].back());
t[from].pop_back();
// from = the index of the tower with the smallest ring that has not just been moved: (to+1)%3 or (to+2)%3
if (t[(to+1)%3].back()<t[(to+2)%3].back())
from = (to+1)%3;
else
from =(to+2)%3;
// candidate = the ring on top of the t[from] tower
candidate = t[from].back();
// to = the index of the closest tower on which the candidate can be placed: (from+1)%3 or (from+2)%3
// (compare the candidate with the ring on the closer tower; which tower is "closer" depends on whether n is odd or even)
if (n%2==1){
if(t[from].back()<t[(to+1)%3].back())
to = (from+1)%3;
else
to = (from+2)%3;
if(t[from].back()<t[(from+1)%3].back())
to = (from+1)%3;
else
to = (from+2)%3;
candidate = t[from].back();
}else{
if(t[(from+1)%3].back()<t[(to+2)%3].back())
to = (from+1)%3;
else
to = (from+2)%3;
if(t[from].back()<t[(from+2)%3].back())
to = (from+2)%3;
else
to = (from+1)%3;
candidate = t[from].back();
}
}
return 0;
}