1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <stdio.h> int cnt; void hanoi(int n, char x, char y, char z) { if (n <= 0) return; else { hanoi(n - 1, x, y, z); printf("move %d from %c to %c\n", n, x, y); cnt++; hanoi(n - 1, z, y, x); printf("move %d from %c to %c\n", n, y, z); cnt++; hanoi(n - 1, x, y, z); } } int main() { int n; printf("input n: "); scanf("%d", &n); hanoi(n, 'A', 'B', 'C'); printf("总次数:%d\n", cnt); return 0; }
|