Write a java program to solve the Tower of Hanoi problem using Recursion.

Tower of Hanoi is a game or puzzle of rods/towers in which a certain number of disks of different sizes needs to be transferred from one tower to another.

The puzzle starts with 3 different size disks in ascending order, with the smallest one at the top.

The aim is to move all the disk in the same order to destination tower abiding the following rules:

  1. One disk should be moved at a time.
  2. Larger disk should not be placed at the top of a smaller disk.

Initially, we have this stack

Tower of Hanoi

We want to achieve this by following the rules.

Tower of Hanoi Java

To solve the Tower of Hanoi problem we will use recursion because each subset of disks is itself follow tower of Hanoi pattern.

Tower of Hanoi using Recursion – Algorithm

Suppose we are given 3 (n) disk as stated in the first diagram and asked to solve this using recursion. And we also know that putting large disk over small ones is not allowed.

The trick is to assume that we are given only two disks (as stated in the picture).

C program to solve Tower of Hanoi

Now we need to shift the upper disk i.e n-1 (which actually contains 2 Disk in the current scenario) to B so that we can shift the last disk (n-th) to C.

The main point is we will not do this. The recursive function will take the responsibility to shift n-1 disks (2 disks in this case) to B.


where rodFrom = A , rodTo = B and rodMiddle = C will be used as auxiliary rod by the recursive function.

Tower of Hanoi algorithm

Now we need to shift last disk (nth or largest disk) to rod C. So we will do this Just by outputting the statement.

System.out.println("Disk "+n+" moved from "+rodFrom+" to "+rodTo)

where n=3, rodFrom = A and rodTo = C .

Tower of Hanoi recursion

Now again the n-1 disk (2 disks) in rod B need to be shifted to C with the help of rod A. Since there are multiple disk i.e n-1, so let the recursive function handle this task. So we will write


where rodFrom = B , rodTo = C and rodMiddle = A will be used as auxiliary rod by the recursive function.

Finally, we will get this i.e Tower of Hanoi solved.

Tower of Hanoi using Recursion

Let’s solve the Tower of Hanoi in Java.


Tower of Hanoi Java Output

If you have any problem in understanding the concept or have any suggestion then comment below.

Leave a Reply

Close Menu