Skip to content

Commit 3c48a25

Browse files
authored
Create TowerOfHanoi.java
1 parent 013d122 commit 3c48a25

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class TowerOfHanoi {
2+
3+
// Method to solve Tower of Hanoi
4+
public static void solveTowerOfHanoi(int n, char source, char auxiliary, char target) {
5+
// Base case: If there is only one disk, move it from source to target
6+
if (n == 1) {
7+
System.out.println("Move disk 1 from " + source + " to " + target);
8+
return;
9+
}
10+
11+
// Move n-1 disks from source to auxiliary, using target as a temporary peg
12+
solveTowerOfHanoi(n - 1, source, target, auxiliary);
13+
14+
// Move the nth disk from source to target
15+
System.out.println("Move disk " + n + " from " + source + " to " + target);
16+
17+
// Move the n-1 disks from auxiliary to target, using source as a temporary peg
18+
solveTowerOfHanoi(n - 1, auxiliary, source, target);
19+
}
20+
21+
public static void main(String[] args) {
22+
int numberOfDisks = 3; // You can change the number of disks here
23+
solveTowerOfHanoi(numberOfDisks, 'A', 'B', 'C'); // A, B and C are names of rods
24+
}
25+
}

0 commit comments

Comments
 (0)