-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathTower_Of_Hanoi.java
More file actions
44 lines (34 loc) · 1.46 KB
/
Tower_Of_Hanoi.java
File metadata and controls
44 lines (34 loc) · 1.46 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
class Solution {
public int towerOfHanoi(int n, int from, int to, int aux) {
if (n == 0) {
return 0;
}
int moves1 = towerOfHanoi(n - 1, from, aux, to);
System.out.println("Move disk " + n + " from rod " + from + " to rod " + to);
int move2 = 1;
int moves3 = towerOfHanoi(n - 1, aux, to, from);
return moves1 + move2 + moves3;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Solution solver = new Solution();
System.out.println("--- Tower of Hanoi Solver (Moves and Count) ---");
System.out.print("Enter the number of disks (n): ");
if (scanner.hasNextInt()) {
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Please enter a non-negative number of disks.");
} else {
System.out.println("\n--- Sequence of Moves ---");
// Rods are conventionally 1 (from), 3 (to), 2 (aux)
int moves = solver.towerOfHanoi(n, 1, 3, 2);
System.out.println("-------------------------");
System.out.println("Total minimum moves required for " + n + " disks: " + moves);
}
} else {
System.out.println("Invalid input. Please enter an integer.");
}
scanner.close();
}
}