hanoi.c (811B)
1 /* Exercise 5.39 */ 2 3 #include <stdio.h> 4 5 int hanoi(int, int, int, int); 6 7 int main() 8 { 9 int d = 4; /* disks number */ 10 11 printf("Total moves: %d\n", hanoi(d, 1, 3, 2)); 12 13 return 0; 14 } /* E0F main */ 15 16 17 /* Move the disks of the Hanoi towers */ 18 int hanoi(int disks, int p_src, int p_dst, int p_tmp) 19 { 20 static int moves = 0; 21 ++moves; 22 23 if(disks == 1) { 24 printf("%d => %d\n", p_src, p_dst); 25 } 26 else { 27 /* 1. Move n - 1 disks from pole 1 to 2, using the 3 as temp pole */ 28 /* 2. Move the latest disk (largest) from pole 1 to 3 */ 29 /* 3. Move the n - 1 disks from pole 2 to 3, using the 1 as temp pole */ 30 31 hanoi(disks - 1, p_src, p_tmp, p_dst); 32 printf("%d => %d\n", p_src, p_dst); 33 hanoi(disks - 1, p_tmp, p_dst, p_src); 34 } 35 36 return moves; 37 } /* eof hanoi() */ 38