#include <stdio.h>
void towerOfHanoi(int n, char source, char target, char auxiliary) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, target);
return;
}
towerOfHanoi(n - 1, source, auxiliary, target); // move n-1 disks to auxiliary
printf("Move disk %d from %c to %c\n", n, source, target); // move nth disk to target
towerOfHanoi(n - 1, auxiliary, target, source); // move n-1 disks from auxiliary to target
}
int main() {
int n = 3;
printf("Tower of Hanoi moves for %d disks:\n", n);
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}base case: move single disk directly
towerOfHanoi(n - 1, source, auxiliary, target);
move top n-1 disks to auxiliary peg
printf("Move disk %d from %c to %c\n", n, source, target);
move largest disk to target peg
towerOfHanoi(n - 1, auxiliary, target, source);
move n-1 disks from auxiliary to target peg
Tower of Hanoi moves for 3 disks:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C