題目說明
三根柱子(A、B、C),一開始有由大到小n個圓盤(1,2,3,4,5…n)在A上,求如何將所有移動到C。大盤不得在小盤之上一次只能移動一個非移動中的盤子需在柱子上
輸入:n不超過15
原題連結:
程式碼
#include <iostream>
using namespace std;
void solution(int N,int from,int to){
string a[3]={"A","B","C"};
if(N>1){
int mid=3-(from+to);
solution(N-1,from,mid);
cout<<"Move ring "<<N<<" from "<<a[from]<<" to "<<a[to]<<endl;
solution(N-1,mid,to);
}else{
cout<<"Move ring "<<N<<" from "<<a[from]<<" to "<<a[to]<<endl;
}
}
int main()
{
int N;
while(cin>>N){
solution(N,0,2);
}
}
解題重點:
- 先在紙上思考遞迴的數學公式
- 轉換成程式的形式