Data Structure & Algorithm in Java

⌘K
  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Recursion
  5. Tower of Hanoi(TOH) Problem

Tower of Hanoi(TOH) Problem

Highlight the explanation of Tower of Hanoi(TOH) Problem:

  • The Tower of Hanoi (TOH) problem is a classic problem in computer science and mathematics that can be elegantly solved using recursion.
  • The problem involves moving a stack of disks from one peg to another peg, with the constraint that only one disk can be moved at a time, and a larger disk cannot be placed on top of a smaller disk.

Here’s a brief explanation of the problem:

  • There are three pegs (or rods), typically named source, destination, and auxiliary.
  • Initially, all disks are stacked in ascending order of size on the source peg.
  • The goal is to move all the disks from the source peg to the destination peg, using the auxiliary peg for temporary storage, following the rules:
    1. Only one disk can be moved at a time.
    2. A larger disk cannot be placed on top of a smaller disk.
    3. All disks must be moved from the source peg to the destination peg.
1 8V5n0SbnWUfe0J1IT3IeQg

Initially, all the disks are placed on one rod, one over the other in ascending order of size similar to a cone-shaped tower. A disk cannot be placed on top of a smaller disk.

  • Only one disc can be moved at a time.
  • Only the top disc of one stack can be transferred to the top of another stack or an empty rod.
  • Larger discs cannot be stacked over smaller ones.
  • The complexity of this problem can be mapped by evaluating the number of possible moves.
  • The least movements needed to solve the Tower of Hanoi problem with n discs are 2n-1

The Tower of Hanoi recursive algorithm involves the following major steps: Recursively move disks from the source rod to the auxiliary rod. Move the nth disk from the source rod to the target rod.

7
ublic class TowerOfHanoi {
    public static void towerOfHanoi(int n, char source, char destination, char auxiliary) {
        if (n == 1) {
            System.out.println("Move disk 1 from " + source + " to " + destination);
            return;
        }
        towerOfHanoi(n - 1, source, auxiliary, destination);
        System.out.println("Move disk " + n + " from " + source + " to " + destination);
        towerOfHanoi(n - 1, auxiliary, destination, source);
    }

    public static void main(String[] args) {
        int n = 3; // Number of disks
        towerOfHanoi(n, 'A', 'C', 'B'); // A, B, and C are pegs
    }
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *