Online Compiler C

#include <stdio.h> void hanoi(int n, int from, int to, int temp){ if(n==1){ printf("%d %d %d\n",n,from,to); return; } if(n>1){ hanoi(n-1, from, to, temp); printf("%d %d %d\n",n,from,to); hanoi(n-1, from, to, temp); } } int main() { int x; scanf("%d", &x); hanoi(x, 1, 3, 2); return 0; }
这段代码试图实现汉诺塔问题的递归解法,但逻辑有误。当前代码在递归调用时,每次都将盘子从 `from` 移到 `to`,没有正确利用 `temp` 作为辅助柱子。

- 在递归调用 `hanoi(n-1, from, to, temp)` 中,你传递的参数顺序不对。对于汉诺塔,移动 n-1 个盘子时,应该先把它们从 `from` 移到 `temp`,而不是直接移到 `to`。你需要检查递归调用时三个柱子的角色分配是否正确。
- 中间的 `printf` 语句打印的是移动最底下的盘子,这一步是正确的。但前后的递归调用参数需要调整,确保小盘子先借助辅助柱子移动,最后再移回目标柱子。