-
Notifications
You must be signed in to change notification settings - Fork 1
/
hanoi.cpp
55 lines (46 loc) · 1.42 KB
/
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
#include <iterator>
#include <iostream>
#include <vector>
class Hanoi {
using tower = unsigned int;
using size = unsigned int;
std::vector<tower> state; // disk number i is on tower state[i]
public:
Hanoi(std::initializer_list<tower> init) : state(init) {}
void solve(tower target) {
printState(); // initial state
solveRec(state.size(), target);
}
private:
void solveRec(size disks, tower target) {
if (disks == 0) {
return;
}
// the tower of the largest disk at this depth of recursion
tower &largest = state[state.size() - disks];
if (largest == target) {
// the largest disk is already on the target tower
solveRec(disks - 1, target);
} else {
// move disks above the largest to the intermediate tower
solveRec(disks - 1, other(largest, target));
// move the largest disk to the target
largest = target;
printState();
// move back the disks on the largest
solveRec(disks - 1, target);
}
}
void printState() {
std::copy(state.cbegin(), state.cend(),
std::ostream_iterator<tower>(std::cout));
std::cout << std::endl;
}
static inline tower other(tower t1, tower t2) {
return 3 - t1 - t2;
}
};
int main() {
Hanoi{ 0, 0, 0, 0, 0 }.solve(2);
return 0;
}