forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowerOfHanoiSmart.java
More file actions
27 lines (20 loc) · 847 Bytes
/
TowerOfHanoiSmart.java
File metadata and controls
27 lines (20 loc) · 847 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
27
import java.util.Scanner;
public class TowerOfHanoiSmart {
public static int solveHanoi(int n, char source, char auxiliary, char destination) {
if (n == 0) return 0;
int moves = solveHanoi(n - 1, source, destination, auxiliary);
System.out.println("Move disk " + n + " from " + source + " to " + destination);
moves++;
moves += solveHanoi(n - 1, auxiliary, source, destination);
return moves;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = sc.nextInt();
System.out.println("\nSteps to solve Tower of Hanoi:");
int totalMoves = solveHanoi(n, 'A', 'B', 'C');
System.out.println("\nTotal moves required: " + totalMoves);
sc.close();
}
}