Java Program for Tower of Hanoi Problem

Source code for Tower of Hanoi problem in Java

// Write a program in Java language to find out the solution for Tower of Hanoi problem with output and source code.
import java.io.*;
class TowerOfHanoi
{
   public static void main (String args[]) throws IOException
   {
     BufferedReader in = new BufferedReader
     (new InputStreamReader (System.in));
     int x;
     System.out.print("No. of disks? ");
     x = Integer.parseInt(in.readLine());
     hanoi(x);
   }
   static void hanoi(int n)
   {
     moveTower (n, 'A', 'B', 'C');
   }
  static void moveTower (int ht, char f, char t, char i)
   {
     if (ht > 0)
     {
       moveTower (ht-1, f, i, t);
       moveRing (ht,f,t);
       moveTower (ht-1,i,t,f);
     }
   }
  static void moveRing (int d, char f, char t)
   {
     System.out.println
     ("Move ring " + d + " from " + f + " to " + t);
   }
}

Output of Tower of Hanoi problem

Output of Tower of hanoi problem in Java with source code

What is Tower of hanoi problem ?

The Tower of Hanoi problem is a very famous gaming puzzle which is also known as by the name of Tower of Brahma or Lucas Tower. This problem consists of 3 rods, and a number of disks which can slide onto the rod. In this game puzzle, we have to arrange the each given disks in such an order that no disk can be placed on top of a smaller disk, with few rules. So when we design the Tower of hanoi problem in programming language we have to take care of all these rules in our program code. In Tower of Hanoi problem, we can move only one disk at a time, i.e. multiple moves are not allowed.

0 comments:

Post a Comment