Implementing Tower of Hanoi Problem in Java

The Tower of Hanoi 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 conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  1. Only one disk can be moved at a time.
  2. 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.
  3. No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n – 1, where n is the number of disks.

(Via Wikipedia)


Here is java implementation of this problem. The program takes count of pegs as input and displays the steps to be followed to solve the problem.

import java.io.*;
public class TowersOfHanoi 
{
    public static int count=0;
    public static void main(String[] args) throws IOException
    {
        BufferedReader obj= new BufferedReader(new InputStreamReader(System.in));
        int n;
        System.out.println("Enter no of pegs:");
        n=Integer.parseInt(obj.readLine());
        hanoi(n,'A','C','B');
        count++;
        System.out.println("No of steps :"+count);
    }
    static void hanoi(int n,char from,char to,char aux)
     {
         if(n==1)
         {
             System.out.println("Move Disk 1 From "+from+" To "+to);
         }
         else
         {
            hanoi(n-1,from,aux,to); 
            System.out.println("Move disk "+n +" From "+from+" To "+to);
            count++;
            hanoi(n-1,aux,to,from);
            count++;
         }
     }
}

/* Output
Enter no of pegs:
3
Move Disk 1 From A To C
Move disk 2 From A To B
Move Disk 1 From C To B
Move disk 3 From A To C
Move Disk 1 From B To A
Move disk 2 From B To C
Move Disk 1 From A To C
No of steps :7
*/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.