The Tower of Hanoi (also called the Tower of Brahma or Lucas’ Tower and sometimes pluralized) is a mathematical game or 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 in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a canonical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
- No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
Recursive Algorithm
Move the disc from start pole to end pole
Recursive Case – When n > 1
Step 1: Move (n-1) discs from start pole to auxiliary pole.
Step 2: Move the last disc from start pole to end pole.
Step 3: Move the (n-1) discs from auxiliary pole to end pole.
Steps 1 and 3 are recursive invocations of the same procedure.
<pre>import java.util.Scanner;
/**
* java program to implement tower of hanoi
* Created by sani kamal on 07-May-17.
*/
public class TowerOfHanoi {
//main function
public static void main(String[] args) {
System.out.println("Enter number of disc:");
Scanner sc = new Scanner(System.in);
int numberOfDiscs = sc.nextInt();
moveDiscs(numberOfDiscs, "A", "B", "C");
}
public static void moveDiscs(int n, String start, String middle, String end) {
//Moved n-th disc to the end pole
if (n == 1) {
System.out.println("Move " + n + " disc from " + start + " to " + end);
} else {
//Move n-1 discs from start pole to the midle
moveDiscs(n - 1, start, end, middle);
System.out.println("Move " + n + " disc from " + start + " to " + end);
//Move n-1 discs from middle pole to the end
moveDiscs(n - 1, middle, start, end);
}
}
}</pre>
