Skip to content

Commit 9ca3a46

Browse files
Add Tower of Hanoi recursion solution
1 parent b76962d commit 9ca3a46

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class TowerOfHanoi {
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) {
11+
12+
// Base case: only one disk
13+
if (n == 1) {
14+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
15+
return;
16+
}
17+
18+
// Step 1: Move n-1 disks from source to helper
19+
towerOfHanoi(n - 1, src, dest, helper);
20+
21+
// Step 2: Move nth disk from source to destination
22+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
23+
24+
// Step 3: Move n-1 disks from helper to destination
25+
towerOfHanoi(n - 1, helper, src, dest);
26+
}
27+
28+
public static void main(String[] args) {
29+
int n = 3; // Number of disks
30+
towerOfHanoi(n, 'A', 'B', 'C');
31+
}
32+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class TowerOfHanoi {
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) {
11+
12+
// Base case: only one disk
13+
if (n == 1) {
14+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
15+
return;
16+
}
17+
18+
// Step 1: Move n-1 disks from source to helper
19+
towerOfHanoi(n - 1, src, dest, helper);
20+
21+
// Step 2: Move nth disk from source to destination
22+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
23+
24+
// Step 3: Move n-1 disks from helper to destination
25+
towerOfHanoi(n - 1, helper, src, dest);
26+
}
27+
28+
public static void main(String[] args) {
29+
int n = 3; // Number of disks
30+
towerOfHanoi(n, 'A', 'B', 'C');
31+
}
32+
}

0 commit comments

Comments
 (0)