三根柱子 A、B、C,A 上叠着 n 个盘子,大的在下。一次只能搬一个,大盘子不能压在小盘子上。补全 hanoi(n, from, via, to):借助 via,把 n 个盘子从 from 搬到 to,每一步显示成 A->C。程序搬 3 个盘子,最后显示一共几步。
A->C A->B C->B A->C B->A B->C A->C 7
#include <stdio.h>
int moves = 0;
void hanoi(int n, char from, char via, char to) {
if (n == 1) {
printf("%c->%c\n", from, to);
moves++;
return;
}
// 在这里写:先把上面 n-1 个盘子从 from 搬到 via
printf("%c->%c\n", from, to);
moves++;
// 在这里写:再把那 n-1 个盘子从 via 搬到 to
}
int main(void) {
hanoi(3, 'A', 'B', 'C');
printf("%d\n", moves);
return 0;
}
写好了先点「运行」试试示例,没问题再点「提交」。