Applying Recursion to Solve Problems
Recursion is particularly useful for solving problems that have a recursive structure or can be broken down into smaller, similar subproblems. Let's look at a classic example: the Tower of Hanoi puzzle.
Tower of Hanoi:
The puzzle consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. The objective is to move the entire stack to another rod, obeying the following rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No larger disk may be placed on top of a smaller disk.
Here's a recursive solution to the Tower of Hanoi problem:
public class TowerOfHanoi {
public static void solveTowerOfHanoi(int n, char source, char auxiliary, char destination) {
// Base case: If only one disk, move it directly
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + destination);
return;
}
// Move n-1 disks from source to auxiliary using destination as auxiliary
solveTowerOfHanoi(n - 1, source, destination, auxiliary);
// Move the nth disk from source to destination
System.out.println("Move disk " + n + " from " + source + " to " + destination);
// Move n-1 disks from auxiliary to destination using source as auxiliary
solveTowerOfHanoi(n - 1, auxiliary, source, destination);
}
public static void main(String[] args) {
int numberOfDisks = 3;
solveTowerOfHanoi(numberOfDisks, 'A', 'B', 'C');
}
}
This recursive solution breaks down the problem into smaller subproblems, moving n-1 disks recursively. Try running this code and observe how it solves the Tower of Hanoi puzzle step by step. Can you visualize the process for a small number of disks?