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:
- Only one disk can be moved at a time.
- A larger disk cannot be placed on top of a smaller disk.
- All disks must be moved from the source peg to the destination peg.
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.
How can we solve the problem of Tower of Hanoi(TOH)?
The Tower of Hanoi problem is solved using the set of rules given below:
- 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
Tower of Hanoi using recursion
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.
Here’s an example implementation of the Tower of Hanoi problem in Java using recursion:
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
}
}