Tower Of Hanoi Algorithm
The Tower of Hanoi Algorithm is a classic puzzle-solving method that was invented by the French mathematician Edouard Lucas in 1883. The objective of this puzzle is to move a stack of disks, which are of varying sizes and initially arranged in ascending order of size, from one peg to another, following certain rules. The puzzle consists of three pegs and a given number of disks. The rules state that you can only move one disk at a time, and a larger disk can never be placed on top of a smaller one. The algorithm aims to determine the minimum number of moves required to accomplish this task, which grows exponentially as the number of disks increases.
The Tower of Hanoi Algorithm can be solved using recursion, a programming technique that involves a function calling itself to break the problem down into smaller, more manageable subproblems. The algorithm moves the top n-1 disks to an auxiliary peg, then moves the largest disk to the target peg, and finally, moves the n-1 disks from the auxiliary peg to the target peg. The base case for the recursion is when there is only one disk, in which case it's simply moved to the target peg. The Tower of Hanoi Algorithm not only provides a solution to the classic puzzle but also has real-world applications in computer science, particularly in data backup systems, file management, and the study of algorithms and problem-solving techniques.
package Others;
import java.util.Scanner;
class TowerOfHanoi {
public static void shift(int n, String startPole, String intermediatePole, String endPole) {
// if n becomes zero the program returns thus ending the loop.
if (n == 0) {
return;
}
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
shift(n - 1, startPole, endPole, intermediatePole);
System.out.println("%nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
shift(n - 1, intermediatePole, startPole, endPole);
}
public static void main(String[] args) {
System.out.print("Enter number of discs on Pole 1: ");
Scanner scanner = new Scanner(System.in);
int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
scanner.close();
}
}