Tower Of Hanoi using recursion
Wed Oct 09 2024 18:26:01 GMT+0000 (Coordinated Universal Time)
Saved by
@wayneinvein
public class TowerOfHanoi {
public static void solve(int n, char source, char target, char auxiliary) {
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + target);
return;
}
solve(n - 1, source, auxiliary, target);
System.out.println("Move disk " + n + " from " + source + " to " + target);
solve(n - 1, auxiliary, target, source);
}
public static void main(String[] args) {
int n = 3; // Number of disks
solve(n, 'A', 'C', 'B'); // A, B and C are the names of the rods
}
}
content_copyCOPY
Comments