The tower of Hanoi 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 conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying 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.
Java code:
public class Hanoi { private static int i = 1; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int n; System.out.print("Please enter the number of dish:"); Scanner scan = new Scanner(System.in); n = scan.nextInt(); hanoi(n, 'A', 'B', 'C'); } public static void hanoi(int n, char a, char b, char c){ if(n>0){ hanoi(n-1, a, c, b); System.out.println("Step " + i + ". Move dish " + n + " from pile " + a + " to " + b); i++; hanoi(n-1, c, b, a); } }}
Input:
Please enter the number of dish:3
Output:
Step 1. Move dish 1 from pile A to BStep 2. Move dish 2 from pile A to CStep 3. Move dish 1 from pile B to CStep 4. Move dish 3 from pile A to BStep 5. Move dish 1 from pile C to AStep 6. Move dish 2 from pile C to BStep 7. Move dish 1 from pile A to B