×

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

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.