|
1 | | -public class TowerOfHanoi { |
| 1 | +package com.thealgorithms.recursion; |
2 | 2 |
|
3 | | - // Recursive function to solve Tower of Hanoi |
4 | | - // Time complexity : O(2^n) |
5 | | - // Space complexity:O(n) (Recursion Stack) |
6 | | - // n : number of disks |
7 | | - // src : source rod |
8 | | - // helper : auxiliary rod |
9 | | - // dest : destination rod |
10 | | - public static void towerOfHanoi(int n, char src, char helper, char dest) { |
| 3 | +/** |
| 4 | + * Tower of Hanoi problem using recursion. |
| 5 | + * |
| 6 | + * <p>Time Complexity: O(2^n)</p> |
| 7 | + * <p>Space Complexity: O(n) (recursion stack)</p> |
| 8 | + */ |
| 9 | +public final class TowerOfHanoi { |
| 10 | + |
| 11 | + private TowerOfHanoi() { |
| 12 | + // Utility class |
| 13 | + } |
11 | 14 |
|
12 | | - // Base case: only one disk |
| 15 | + public static void towerOfHanoi(int n, char src, char helper, char dest) { |
13 | 16 | if (n == 1) { |
14 | 17 | System.out.println("Move disk " + n + " from " + src + " to " + dest); |
15 | 18 | return; |
16 | 19 | } |
17 | 20 |
|
18 | | - // Step 1: Move n-1 disks from source to helper |
19 | 21 | towerOfHanoi(n - 1, src, dest, helper); |
20 | | - |
21 | | - // Step 2: Move nth disk from source to destination |
22 | 22 | System.out.println("Move disk " + n + " from " + src + " to " + dest); |
23 | | - |
24 | | - // Step 3: Move n-1 disks from helper to destination |
25 | 23 | towerOfHanoi(n - 1, helper, src, dest); |
26 | 24 | } |
27 | | - |
28 | | - public static void main(String[] args) { |
29 | | - int n = 3; // Number of disks |
30 | | - towerOfHanoi(n, 'A', 'B', 'C'); |
31 | | - } |
32 | 25 | } |
| 26 | + |
0 commit comments