The Tower of Hanoi Algorithm in Java: A Detailed Guide

javafullstackdev

JavaFullStackDev.in

Posted on September 4, 2024

The Tower of Hanoi Algorithm in Java: A Detailed Guide

The Tower of Hanoi is a classic algorithmic problem often used to teach recursion in computer science. The problem involves three rods and a number of disks of different sizes that can slide onto any rod. The puzzle starts with the disks neatly stacked in ascending order of size on one rod, the smallest at the top, forming a conical shape.

Problem Statement

Given three rods (A, B, and C) and n disks, where all disks are initially placed on rod A, the goal is to move all disks from rod A to rod C, following these rules:

  1. Only one disk can be moved at a time.
  2. A disk can only be placed on top of a larger disk or an empty rod.
  3. All disks must be moved to rod C using rod B as an auxiliary rod.

Recursion and the Tower of Hanoi

The Tower of Hanoi is a perfect example of a problem that can be solved using recursion. The recursive solution involves breaking down the problem into smaller sub-problems, which eventually leads to a base case.

Steps to Solve Tower of Hanoi

  1. Base Case: If there is only one disk, move it directly from rod A to rod C.
  2. Recursive Case:
    • Move n-1 disks from rod A to rod B, using rod C as an auxiliary rod.
    • Move the nth disk from rod A to rod C.
    • Move the n-1 disks from rod B to rod C, using rod A as an auxiliary rod.

Java Implementation

Below is a Java implementation of the Tower of Hanoi algorithm.

public class TowerOfHanoi {

    // Recursive function to solve the Tower of Hanoi puzzle
    public static void solve(int n, char sourceRod, char targetRod, char auxiliaryRod) {
        // Base case: If there's only one disk, move it from source to target
        if (n == 1) {
            System.out.println("Move disk 1 from rod " + sourceRod + " to rod " + targetRod);
            return;
        }

        // Move n-1 disks from source to auxiliary, using target as auxiliary
        solve(n - 1, sourceRod, auxiliaryRod, targetRod);

        // Move the nth disk from source to target
        System.out.println("Move disk " + n + " from rod " + sourceRod + " to rod " + targetRod);

        // Move the n-1 disks from auxiliary to target, using source as auxiliary
        solve(n - 1, auxiliaryRod, targetRod, sourceRod);
    }

    public static void main(String[] args) {
        int n = 3; // Number of disks
        solve(n, 'A', 'C', 'B'); // A, B, and C are names of rods
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

  1. solve Method:

    • This method takes four arguments:
      • n: The number of disks.
      • sourceRod: The rod from which the disks are to be moved.
      • targetRod: The rod to which the disks are to be moved.
      • auxiliaryRod: The rod used as an auxiliary.
    • The method is recursive and works by breaking the problem down into smaller sub-problems.
  2. Base Case:

    • If n is 1, the method simply prints out the move from the source rod to the target rod.
  3. Recursive Case:

    • The function first calls itself to move n-1 disks from the source rod to the auxiliary rod.
    • It then moves the nth disk from the source rod to the target rod.
    • Finally, it moves the n-1 disks from the auxiliary rod to the target rod.
  4. Main Method:

    • The main method initializes the number of disks and calls the solve method to start the process.

Example Walkthrough

Let's walk through an example with 3 disks:

  • Initial State: All disks are on rod A.
  • Step 1: Move the top 2 disks from rod A to rod B (using rod C as auxiliary).
  • Step 2: Move the 3rd disk from rod A to rod C.
  • Step 3: Move the 2 disks from rod B to rod C (using rod A as auxiliary).

Here's what the output would look like:

Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Enter fullscreen mode Exit fullscreen mode

Time Complexity

The time complexity of the Tower of Hanoi algorithm is (O(2^n - 1)), which simplifies to (O(2^n)). This is because each move of a disk can be broken down into two recursive calls, and with every increase in n, the number of moves doubles and adds one.

Space Complexity

The space complexity is (O(n)) due to the recursive call stack, where n is the number of disks.

Conclusion

The Tower of Hanoi is an excellent problem to understand the power of recursion. Although the time complexity grows exponentially with the number of disks, the algorithm provides a clear and efficient method to solve the problem using recursive function calls. This Java implementation can be easily adapted to solve the Tower of Hanoi problem with any number of disks, and understanding it is a great step forward in mastering recursion in Java.

Final Thoughts

Recursion is a fundamental concept in programming, and the Tower of Hanoi is a perfect example to practice and understand it. By breaking down the problem into smaller sub-problems, recursion simplifies what might initially seem like a daunting task. Mastering such problems will not only boost your confidence in handling recursive algorithms but also prepare you for more complex challenges in computer science.


This blog post should provide a comprehensive understanding of how to implement the Tower of Hanoi algorithm in Java, along with the conceptual background necessary to grasp the underlying recursion.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
javafullstackdev
JavaFullStackDev.in

Posted on September 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About