汉若塔圆盘递归c语言
时间: 2023-11-07 13:47:33 浏览: 42
当然可以!下面是一个使用递归实现汉诺塔问题的 C 语言代码示例:
```c
#include <stdio.h>
void move(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
move(n-1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
move(n-1, aux, to, from);
}
int main() {
int num_disks;
printf("Enter the number of disks: ");
scanf("%d", &num_disks);
printf("Tower of Hanoi solution:\n");
move(num_disks, 'A', 'C', 'B');
return 0;
}
```
这段代码会先要求用户输入要移动的圆盘数量,然后调用 `move` 函数来解决汉诺塔问题。在 `move` 函数中,我们首先检查基本情况(只有一个圆盘时直接移动),否则我们将 n-1 个圆盘从 from 柱移动到 aux 柱,然后将剩余的一个圆盘从 from 柱移动到 to 柱,最后将 n-1 个圆盘从 aux 柱移动到 to 柱。
希望这可以帮到你!如果有任何问题,请随时提问。