|
| 1 | +// https://en.wikipedia.org/wiki/Tower_of_Hanoi |
| 2 | +/** |
| 3 | + * TowerOfHanoi.java |
| 4 | + * |
| 5 | + * This program demonstrates the recursive solution for the Tower of Hanoi problem. |
| 6 | + * It prints the sequence of moves required to move n disks from source rod to target rod. |
| 7 | + */ |
| 8 | +public class TowerOfHanoi { |
| 9 | + |
| 10 | + /** |
| 11 | + * Solves the Tower of Hanoi problem recursively. |
| 12 | + * |
| 13 | + * @param n Number of disks |
| 14 | + * @param from Source rod |
| 15 | + * @param to Target rod |
| 16 | + * @param aux Auxiliary rod |
| 17 | + */ |
| 18 | + public static void solveTowerOfHanoi(int n, char from, char to, char aux) { |
| 19 | + if (n == 1) { |
| 20 | + System.out.println("Move disk 1 from " + from + " to " + to); |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + // Move n-1 disks from source to auxiliary |
| 25 | + solveTowerOfHanoi(n - 1, from, aux, to); |
| 26 | + |
| 27 | + // Move the nth disk from source to target |
| 28 | + System.out.println("Move disk " + n + " from " + from + " to " + to); |
| 29 | + |
| 30 | + // Move the n-1 disks from auxiliary to target |
| 31 | + solveTowerOfHanoi(n - 1, aux, to, from); |
| 32 | + } |
| 33 | + |
| 34 | + public static void main(String[] args) { |
| 35 | + int numberOfDisks = 3; // You can change this to test with more disks |
| 36 | + System.out.println("Tower of Hanoi solution for " + numberOfDisks + " disks:"); |
| 37 | + solveTowerOfHanoi(numberOfDisks, 'A', 'C', 'B'); |
| 38 | + } |
| 39 | +} |
0 commit comments