The classic mathematical puzzle that demonstrates recursive algorithms. Visualize the solution step by step!
How to Play: The objective is to move all disks from Tower A to Tower C, using Tower B as auxiliary. Only one disk can be moved at a time, and a larger disk cannot be placed on top of a smaller disk.
The Tower of Hanoi is a mathematical puzzle invented by the French mathematician Édouard Lucas in 1883. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top.
Mathematical Significance: The Tower of Hanoi is often used in computer science to teach recursive algorithms. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2^n - 1, where n is the number of disks.
function moveTower(n, source, destination, auxiliary) {
if (n === 1) {
// Move disk 1 from source to destination
moveDisk(source, destination);
} else {
// Move n-1 disks from source to auxiliary
moveTower(n-1, source, auxiliary, destination);
// Move the nth disk from source to destination
moveDisk(source, destination);
// Move n-1 disks from auxiliary to destination
moveTower(n-1, auxiliary, destination, source);
}
}
This recursive algorithm elegantly solves the Tower of Hanoi puzzle. For n disks, the algorithm makes 2^n - 1 moves, which is provably optimal.
| Number of Disks (n) | Minimum Moves (2^n - 1) | Time Complexity | Recursive Calls | Difficulty Level |
|---|---|---|---|---|
| 3 | 7 | O(2^n) | 15 | Easy |
| 4 | 15 | O(2^n) | 31 | Easy |
| 5 | 31 | O(2^n) | 63 | Medium |
| 6 | 63 | O(2^n) | 127 | Medium |
| 7 | 127 | O(2^n) | 255 | Hard |
| 8 | 255 | O(2^n) | 511 | Hard |
| 9 | 511 | O(2^n) | 1023 | Expert |
Classic Tower of Hanoi: The standard puzzle with three towers and n disks. The goal is to move all disks from the first tower to the third tower.
Reve's Puzzle (Four Pegs): A variation with four pegs instead of three. This is also known as the "Tower of Hanoi with four pegs" and has a more complex optimal solution.
Cyclic Hanoi: A variation where the disks can only be moved in one direction (clockwise or counterclockwise) around the three pegs.
Tower of Hanoi with Forbidden Moves: A variation where certain moves between pegs are not allowed, adding additional constraints to the puzzle.
| Disks | Moves | Time |
|---|---|---|
| 3 Disks | - | - |
| 4 Disks | - | - |
| 5 Disks | - | - |
| 6 Disks | - | - |
| 7 Disks | - | - |