-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHanoi_Recursion.cpp
More file actions
44 lines (37 loc) · 931 Bytes
/
Copy pathHanoi_Recursion.cpp
File metadata and controls
44 lines (37 loc) · 931 Bytes
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
#include <iostream>
#include <stack>
/* Classic Hanoi tower problem
Using stacks to represent each tower
*/
using st = std::stack<int>;
struct augmentedStack {
st stack;
std::string name;
};
using as = augmentedStack;
void transferDisk(as& from, as& to) {
to.stack.push(from.stack.top());
std::cout << "Moving " << from.stack.top() << " from " << from.name << " to " << to.name <<"\n";
from.stack.pop();
}
void arrange(as& from, as& aux, as& to, int numDiscs) {
if (numDiscs == 1) {
transferDisk(from, to);
return;
}
arrange(from, to, aux, numDiscs - 1);
transferDisk(from, to);
arrange(aux, from, to, numDiscs - 1);
}
int main() {
int numDiscs = 3;
as initStack, midStack, endStack;
initStack.name = "Source";
midStack.name = "Auxilary";
endStack.name = "Destination";
for (int i=numDiscs-1; i >= 0; i--) {
initStack.stack.push(i);
}
arrange(initStack, midStack, endStack, numDiscs);
return 0;
}