三根柱子 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;
}
寫好了先點「執行」試試示例,沒問題再點「提交」。