Skip to content

Commit 2b50b29

Browse files
Fix Tower of Hanoi formatting and utility class structure
1 parent 3f8a900 commit 2b50b29

File tree

1 file changed

+14
-20
lines changed

1 file changed

+14
-20
lines changed
Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,26 @@
1-
public class TowerOfHanoi {
1+
package com.thealgorithms.recursion;
22

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+
}
1114

12-
// Base case: only one disk
15+
public static void towerOfHanoi(int n, char src, char helper, char dest) {
1316
if (n == 1) {
1417
System.out.println("Move disk " + n + " from " + src + " to " + dest);
1518
return;
1619
}
1720

18-
// Step 1: Move n-1 disks from source to helper
1921
towerOfHanoi(n - 1, src, dest, helper);
20-
21-
// Step 2: Move nth disk from source to destination
2222
System.out.println("Move disk " + n + " from " + src + " to " + dest);
23-
24-
// Step 3: Move n-1 disks from helper to destination
2523
towerOfHanoi(n - 1, helper, src, dest);
2624
}
27-
28-
public static void main(String[] args) {
29-
int n = 3; // Number of disks
30-
towerOfHanoi(n, 'A', 'B', 'C');
31-
}
3225
}
26+

0 commit comments

Comments
 (0)