2022.11.02 PM 11:00 by CBJ
來源 : https://zerojudge.tw/ShowProblem?problemid=a227 出題者 : 2011三龍杯(成附建杯) 標籤 : 遞迴 難易度 : 3
解題想法 : 實作一個函式,功能是把from移到to的位置,以此邏輯下去實作(還需要計算環的編號) 實作技巧 : 寫遞迴(自訂函式)時,先想像它已經是具有完整功能的函式,放心地去用它就對了。
//C language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/a227.c
#include<stdio.h>
void hanoi(char from, char to, char another, int amount, int num){
if(amount==1){
printf("Move ring %d from %c to %c\n",num,from,to);
return;
}
hanoi(from, another, to, amount-1, 1);
hanoi(from, to, another, 1, amount);
hanoi(another, to, from, amount-1, 1);
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
hanoi('A','C','B',n,1);
}
return 0;
}

//C++ language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/a227.cpp
#include<iostream>
using namespace std;
void hanoi(char from, char to, char another, int amount, int num){
if(amount==1){
cout<<"Move ring "<<num<<" from "<<from<<" to "<<to<<"\n";
return;
}
hanoi(from, another, to, amount-1, 1);
hanoi(from, to, another, 1, amount);
hanoi(another, to, from, amount-1, 1);
}
int main(){
int n;
while(cin>>n){
hanoi('A','C','B',n,1);
}
return 0;
}

## Python language
## solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/a227.py
from sys import stdin
def hanoi(From, To, Another, Amount, Num):
if Amount==1:
print(f"Move ring {Num} from {From} to {To}")
return
hanoi(From, Another, To, Amount-1, 1)
hanoi(From, To, Another, 1, Amount)
hanoi(Another, To, From, Amount-1, 1)
for read in stdin:
n=int(read)
hanoi('A','C','B',n,1);

發佈留言