forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowerofHanoi.java
More file actions
26 lines (20 loc) · 937 Bytes
/
TowerofHanoi.java
File metadata and controls
26 lines (20 loc) · 937 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
public class TowerOfHanoi {
public static void solveTowerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + destination);
return;
}
solveTowerOfHanoi(n - 1, source, destination, auxiliary);
System.out.println("Move disk " + n + " from " + source + " to " + destination);
solveTowerOfHanoi(n - 1, auxiliary, source, destination);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of disks: ");
int numberOfDisks = scanner.nextInt();
System.out.println("Steps to solve Tower of Hanoi with " + numberOfDisks + " disks:");
solveTowerOfHanoi(numberOfDisks, 'A', 'B', 'C');
scanner.close();
}
}