×

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java

The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n number of disks of different sizes. The task is to move all the n disks placed at one pole to another pole with the help of an intermediate pole. Follow the rules given below while moving the disks:

Rule 1: We can only move one disk at a time from one pole to another.

Rule 2: Only the topmost disk from any of the three given poles can be stacked to another pole.

Rule 3: The larger size disk can’t be placed on the top of a smaller disk.

The Tower of Hanoi puzzle is one of the prominent applications of recursion.

Let’s observe the Java program of the puzzle.

Filename: TowerOfHanoiExample.java

public class TowerOfHanoiExample
{
// A recursive method to find the solution of the puzzle, called Tower of Hanoi
static void twrOfHanoi(int disk, char fromPole, char toPole, char auxPole)
{
    // handling the base case
    if (disk == 1)
    {
          System.out.println("Moving disk 1 from pole " + fromPole + " to pole " + toPole);
           return;
     }
     // The first recursive call             
     // recursively moving the n - 1 disk from the source pole to the auxiliary pole
     twrOfHanoi(disk - 1, fromPole, auxPole, toPole);
      // move the nth pole from the source pole to the destination pole
      System.out.println("Moving disk " + disk + " from pole " + fromPole + " to pole " + toPole);
      // The second recursive call
      // recursively moving the n - 1 disk from the auxiliary pole to the destination pole
      twrOfHanoi(disk - 1, auxPole, toPole, fromPole);
}
       // The driver method
       public static void main(String argvs[])
       {
               int disks = 3; // total number of disks
               char firstPole = 'A'; // first pole
               char secondPole = 'B'; // second pole
               char thirdPole = 'C'; // third pole
               // invoking the method twrOfHanoi
               twrOfHanoi( disks, firstPole, thirdPole, secondPole );
      }
} 

Output:

 Moving disk 1 from pole A to pole C
Moving disk 2 from pole A to pole B
Moving disk 1 from pole C to pole B
Moving disk 3 from pole A to pole C
Moving disk 1 from pole B to pole A
Moving disk 2 from pole B to pole C
Moving disk 1 from pole A to pole C 

Explanation: In the above program, the three poles has been used to move the disks that are A, B, and C, respectively. Pole A is the source pole, where all the three disks are stacked by default. Pole C is the destination pole, and pole B is the auxiliary pole.

The task is to stack all the disks from the source pole, i.e., pole A to the destination pole, i.e., pole C, with the help of the auxiliary pole, i.e., pole B. The task is accomplished in the three following steps.

Step 1: Recursively move n – 1 disk from pole A to the pole B using pole C as the auxiliary pole.

Step 2: Move the nth disk or the last disk, which is of the largest size, from pole A to pole C.

Step 3: Recursively move n – 1 disk from pole B to the pole C using pole A as the auxiliary pole.

Tower of Hanoi Program in Java
Tower of Hanoi Program in Java

After the completion of the first step, pole A contains only one disk, the largest one. While the second and the third disk get stacked on pole B. Pole C is empty. Here, the pole C has acted as the auxiliary pole. The following diagrams illustrate the same.

Tower of Hanoi Program in Java
Tower of Hanoi Program in Java

Compare the disks positioning of figure-1 and figure-4. We see that pole A, B, and C contain 1, 2, and 0 disks, respectively. Figure-1 shows the initial positioning of the disks, and figure-4 demonstrates the final positioning of disks after the completion of step 1 (the first recursive call). Now, the nth disk is moved from pole A to pole C. After that, we move the remaining disks stacked on pole B to pole C. Consider the following diagrams.

The print statement sandwiched between the recursive calls is used to move the nth pole from the source to the destination pole (see figures 4 & 5). Now, we move to step 3 (figures 6 to 8). Here, pole A acts as the auxiliary pole and B as the source pole. All the disks eventually get stacked to the pole C.

Observe that the output contains 7 statements. Therefore, there are 7 recursive calls. The result of each recursive call is demonstrated in the above figures (figures 2 to 8). Note that, at any step we have not violated the rule to solve the puzzle.

Note: The Java program written above is a generic program and gives correct results even for a large number of disks (change the number of disks from 3 to any desired number and see yourself). For the sake of simplicity, we have chosen only 3 disks.


Related Topics

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.