3.4 In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next rod;
(3) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using Stacks.
#include <iostream>
#include <stack>
using namespace std;
class Tower {
private:
stack<int> s;
int index;
public:
Tower(int idx) : index(idx) {}
int getIndex() {
return index;
}
void push(int disk) {
s.push(disk);
}
int pop() {
int disk = s.top();
s.pop();
return disk;
}
};
void Hanoi(int n, Tower &from, Tower &to, Tower &use) {
if (n > 0) {
Hanoi(n - 1, from, use, to);
int disk = from.pop();
cout << "Move disk " << disk << " from " << from.getIndex() << " to " << to.getIndex() << endl;
to.push(disk);
Hanoi(n - 1, use, to, from);
}
}
int main()
{
Tower from(1);
Tower use(2);
Tower to(3);
int n = 3;
for (int i = n; i > 0; i--) {
from.push(i);
}
Hanoi(n, from, to, use);
return 0;
}