1 // https://en.wikipedia.org/wiki/Tower_of_Hanoi 2 3 #include <iostream> 4 5 // Gives the steps to follow in order to move all the disks from src to dst 6 void move_stack(int disks, int src, int dst, int tmp) 7 { 8 // Base case, move one disk from src to dst 9 if(disks == 1) { 10 printf("%d -> %d\n", src, dst); 11 return; 12 } 13 14 // Move every disk except the biggest one to the tmp peg 15 move_stack(disks - 1, src, tmp, dst); 16 17 // Move the biggest one to the dst peg 18 move_stack(1, src, dst, tmp); 19 20 // Move all the disks on the tmp peg to the dst one 21 move_stack(disks - 1, tmp, dst, src); 22 return; 23 } 24 25 int main (void) { 26 // Move 3 disks from first peg to third peg 27 // using the second peg as temporary 28 move_stack(3, 1, 3, 2); 29 30 return 0; 31 }
