Онлайн компилятор 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; } hanoi(n-1,from,to,temp); printf("%d %d %d\n",n,from,to); hanoi(n-1, temp,from,to); } int main() { int x; scanf("%d",&x); hanoi(x,1,3,2); return 0; }
这段代码试图实现汉诺塔问题的递归解法,但存在逻辑错误。

代码中递归调用的参数顺序不正确。在汉诺塔问题中,你需要将n-1个盘子从起始柱移到辅助柱,然后将第n个盘子从起始柱移到目标柱,最后将n-1个盘子从辅助柱移到目标柱。

- 第一个递归调用 `hanoi(n-1,from,to,temp)` 的参数顺序不对,这里应该把盘子从from移到temp,而不是to。
- 第二个递归调用 `hanoi(n-1, temp,from,to)` 的参数顺序也不对,这里应该把盘子从temp移到to,但参数中from和to的位置需要调整。