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.
function TowerofHanoi($diskCount, $fromPole, $toPole, $viaPole)
{
if ($diskCount == 1)
{
echo "Move disk from pole " . $fromPole . " to pole " . $toPole . "<br/>";
}
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