下面是使用递归算法实现C语言版本的汉诺塔问题:
#include <stdio.h>
void hanoi(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n - 1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n - 1, aux, to, from);
}
int main() {
int n = 3; // 将三个盘子从A移动到C
hanoi(n, 'A', 'C', 'B');
return 0;
}
输出结果:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
该算法使用递归的思想,将问题分解为更小的子问题。首先将 n-1 个盘子从起始柱子(from)移动到辅助柱子(aux),然后将最大的盘子从起始柱子(from)移动到目标柱子(to),最后将 n-1 个盘子从辅助柱子(aux)移动到目标柱子(to)。通过递归调用,将问题规模缩小,直到只剩下一个盘子需要移动。
网友留言: