日期:2025年11月12日
ZeroJudge 題目連結:h089. 疊披薩
解題想法
這題就是河內塔。
Python 程式碼
使用時間約為 0.8 s,記憶體約為 3.1 MB,通過測試。
def hanoi(n, src, aux, dst):
if n == 1:
print(f"from {src:s} to {dst:s}")
return
hanoi(n-1, src, dst, aux)
print(f"from {src:s} to {dst:s}")
hanoi(n-1, aux, src, dst)
hanoi(int(input()), "A", "B", "C")
C++ 程式碼
使用時間約為 64 ms,記憶體約為 52 kB,通過測試。
#include <cstdio>
void hanoi(int n, char src, char aux, char dst) {
if (n == 1) {
printf("from %c to %c\n", src, dst);
return;
}
hanoi(n-1, src, dst, aux);
printf("from %c to %c\n", src, dst);
hanoi(n-1, aux, src, dst);
}
int main() {
int n; scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
沒有留言:
張貼留言