Towers Of Hanoi Algorithm
The towers of hanoi is a mathematical puzzle. We have three towers (or rods or pegs), and a number of disks of different sizes which can slide into any tower.
The puzzle starts with the disks on one tower in ascending order of size, the smallest at the top, making a conical shape.
The objective of the puzzle is to move entire stack on another tower with satisfying below rules:
Rules
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the towers and sliding it onto another tower, on top of the other disks that may already be present on that tower.
- No disk can 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 disks from auxiliary tower to destination tower.
- Now, transferring the top n-1 disks from source to auxiliary tower can be thought as a fresh problem and can be solved in the same manner using recursion.
- Once we solve Towers Of Hanoi with three disks, we can solve it with any number of disks with the same algorithm.
Java Program of Towers Of Hanoi
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.codenuclear; import java.util.Scanner; public class TowersOfHanoi { public void solveTowersOfHanoi(int n, String source, String aux, String dest) { // If only 1 disk, make the move and return. if(n==1) { System.out.println(source+" --> "+dest); return; } // Move top n-1 disks from A to B using C as auxiliary. solveTowersOfHanoi(n-1, source, dest, aux); //Move remaining disks from A to C System.out.println(source+" --> "+dest); // Move n-1 disks from B to C using A as auxiliary solveTowersOfHanoi(n-1, aux, source, dest); } public static void main(String args[]) { TowersOfHanoi obj = new TowersOfHanoi(); System.out.println("Enter number of disks :- "); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.close(); System.out.println("Move disks as below illustration."); obj.solveTowersOfHanoi(n, "A", "B", "C"); } } |
Output