📝 Code 1 (Your Solution 5)
public class Solution {
public static void towerOfHanoi(int n, String src,
String helper, String dest) {
if(n == 1) {
System.out.println("transfer disk " + n +
" from " + src + " to " + dest);
return;
}
// Transfer top n-1 from src to helper using dest
towerOfHanoi(n-1, src, dest, helper);
// Transfer nth from src to dest
System.out.println("transfer disk " + n +
" from " + src + " to " + helper);
// Transfer n-1 from helper to dest using src
towerOfHanoi(n-1, helper, src, dest);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = sc.nextInt();
towerOfHanoi(n, "A", "B", "C");
}
}
⚡ Code 2 (Optimized Version)
public class TowerOfHanoi {
static int steps = 0; // total steps tracker
static void solveHanoi(int n, char source,
char helper, char destination) {
if (n == 1) {
steps++;
System.out.println("Move disk 1 from " +
source + " to " + destination);
return;
}
// Step 1: Move n-1 disks from source to helper
solveHanoi(n - 1, source, destination, helper);
// Step 2: Move nth disk from source to destination
steps++;
System.out.println("Move disk " + n + " from " +
source + " to " + destination);
// Step 3: Move n-1 disks from helper to destination
solveHanoi(n - 1, helper, source, destination);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = sc.nextInt();
steps = 0; // Reset counter
solveHanoi(n, 'A', 'B', 'C');
System.out.println("Total steps = " + steps);
}
}