fork(1) download
  1. #include <stdio.h>
  2. void hanoi(int n, char from, char temp, char to) {
  3. // 终止条件:只有1个圆盘时,直接从源柱移到目标柱
  4. if (n == 1) {
  5. printf("将圆盘 %d 从 %c 移动到 %c\n", n, from, to);
  6. return;
  7. }
  8. // 步骤1:将n-1个圆盘从from移到temp(用to作为辅助)
  9.  
  10. // 步骤2:将第n个圆盘从from移到to
  11. printf("将圆盘 %d 从 %c 移动到 %c\n", n, from, to);
  12. // 步骤3:将n-1个圆盘从temp移到to(用from作为辅助)
  13.  
  14. }
  15. int main() {
  16. int n;
  17. printf("请输入汉诺塔的圆盘数量:");
  18. scanf("%d", &n);
  19.  
  20. hanoi(n, 'A', 'B', 'C');
  21. return 0;
  22. }
Success #stdin #stdout 0s 5344KB
stdin
3
stdout
请输入汉诺塔的圆盘数量:将圆盘 3 从 A 移动到 C