Chapter: Math Class Last Updated: 05-11-2016 13:27:20 UTC

Program:

` ````
/* ............... START ............... */
public class JavaTowerOfHanoi {
private static void hanoi(int disks) {
hanoi(disks, "Pole 1", "Pole 3", "Pole 2");
}
private static void hanoi(int disks, String from, String to, String using) {
if (disks != 0) {
hanoi(disks - 1, from, using, to);
System.out.println("Move disk " + disks + " from " + from + " to " + to);
hanoi(disks - 1, using, to, from);
}
}
public static void main(String[] arg) throws Exception {
hanoi(4);
}
}
/* ............... END ............... */
```

Output

Move disk 1 from Pole 1 to Pole 2 Move disk 2 from Pole 1 to Pole 3 Move disk 1 from Pole 2 to Pole 3 Move disk 3 from Pole 1 to Pole 2 Move disk 1 from Pole 3 to Pole 1 Move disk 2 from Pole 3 to Pole 2 Move disk 1 from Pole 1 to Pole 2 Move disk 4 from Pole 1 to Pole 3 Move disk 1 from Pole 2 to Pole 3 Move disk 2 from Pole 2 to Pole 1 Move disk 1 from Pole 3 to Pole 1 Move disk 3 from Pole 2 to Pole 3 Move disk 1 from Pole 1 to Pole 2 Move disk 2 from Pole 1 to Pole 3 Move disk 1 from Pole 2 to Pole 3

Notes:

- Towers of Hanoi is a famous game.
- In this game there are three poles and N number of disks placed one over another in increasing in size from top to bottom.
- Objective of this game is to move disks from first pole to last pole.
- And the condition is we can not place bigger disk on top of smaller disk.
- Initially all disks placed in first pole smaller disk will be on top and bigger disk will be on bottom.
- We need to move all the disks from from first pole to last pole.
- Rules of tower of Hanoi:
- We can move only one disk at a time.
- At any poi of time larger disk can not be placed on smaller disk.
- In order to solve this problem we have given a second pole so we can use second pole and move disks from first pole to third pole.
- We can solve this using rec recursive procedure.

Tags

Tower Of Hanoi, Java, Math

1 2