The Tower of Hanoi is a mathematical puzzle. 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 on one rod in ascending order of size the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, satisfying the following rules:
- Only one disk may be moved at a time.
- Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
- No disk may be placed on top of a smaller disk.
Algorithm
- move the top n-1 disks from Source to Auxiliary tower,
- Move the nth disk from Source to Destination tower,
- Move the (n-1)th disks from Auxiliary tower to Destination tower.
- Transferring the top (n-1) disks from Source to Auxiliary tower can again be thought of as a fresh problem and can be solved in the same manner. Once we solve Tower of Hanoi with three disks, we can solve it with any number of disks with the above algorithm.
void TowersOfHanoi(int n, char frompeg, char topeg, char auxpeg){
// If only 1 disk then move and return
if(n == 1) {
System.out.println("Move disk 1 from peg "+ frompeg+" to peg "+ topeg);
return;
}
// Move top (n-1) disks from A to B, using C as Auxiliary
TowersOfHanoi(n-1, frompeg, auxpeg, topeg);
//Move remaining disks from A to C
System.out.println("Move disk from peg "+frompeg+" to peg "+ topeg);
// Move (n-1) disks from B to C using A as Auxiliary
TowersOfHanoi(n-1, auxpeg, topeg, frompeg);
}
source: Data Structures and Algorithms Made Easy in Java ( By Narasimha Karumanchi )



