Tower of Hanoi
The Tower of Hanoi (a.k.a Tower of Brahma and Lucas' Tower) is a mathematical game or puzzle.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1. Move only one disk at a time.
2. A larger disk may not be placed ontop of a smaller disk.
3. All disks, except the one being moved, must be on a peg.
/*****Please include following header files*****/
// iostream
/***********************************************/
/*****Please use following namespaces*****/
// std
/*****************************************/
static void TowerofHanoi(int diskCount, int fromPole, int toPole, int viaPole)
{
if (diskCount == 1)
{
cout << "Move disk from pole " << fromPole << " to pole " << toPole << endl;
}
else
{
TowerofHanoi(diskCount - 1, fromPole, viaPole, toPole);
TowerofHanoi(1, fromPole, toPole, viaPole);
TowerofHanoi(diskCount - 1, viaPole, toPole, fromPole);
}
}
Example
TowerofHanoi(4, 1, 2, 3);
Output
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 2