The Tower of Hanoi (also known as the Tower of Brahma) is a mathematical puzzle that consists of three rods and a number of discs of different sizes that can slide onto any rod. The objective of the puzzle is to move all of the discs from the first rod to the third rod, following these rules:
The Tower of Hanoi is a classic example of a recursive problem, as the solution to the puzzle involves breaking it down into smaller subproblems and solving them one at a time.
Here's an example of how you can implement the Tower of Hanoi puzzle in Java using a recursive approach:
public class TowerOfHanoi { public static void solve(int n, char source, char auxiliary, char target) { if (n == 1) { System.out.println("Move disc 1 from " + source + " to " + target); return; } solve(n - 1, source, target, auxiliary); System.out.println("Move disc " + n + " from " + source + " to " + target); solve(n - 1, auxiliary, source, target); } public static void main(String[] args) { int n = 3; // number of discs solve(n, 'A', 'B', 'C'); // solve the puzzle } }
In this example, the solve()
method is a recursive function that takes four arguments: the number of discs, and the names of the three rods (source, auxiliary, and target). The function prints the steps required to solve the puzzle and calls itself recursively to solve the subproblems.
When the number of discs is 1, the function prints a message indicating that the disc should be moved from the source rod to the target rod and returns. When the number of discs is greater than 1, the function first calls itself to solve the subproblem of moving the top n-1 discs from the source rod to the auxiliary rod, then prints a message indicating that the nth disc should be moved from the source rod to the target rod, and finally calls itself to solve the subproblem of moving the n-1 discs from the auxiliary rod to the target rod.
This recursive solution allows the Tower of Hanoi puzzle to be solved for any number of discs, as the solution to the puzzle is built upon the solutions to the smaller subproblems.