[題解] a227 三龍杯 -> 河內之塔

Posted on Sun, Aug 29, 2021 題解 C++

題目說明

三根柱子(A、B、C),一開始有由大到小n個圓盤(1,2,3,4,5…n)在A上,求如何將所有移動到C。大盤不得在小盤之上一次只能移動一個非移動中的盤子需在柱子上

輸入:n不超過15

原題連結:

a227. 三龍杯 -> 河內之塔 - 高中生程式解題系統

河內之塔(Towers of Hanoi)是法國人M.Claus(Lucas)於1883年從泰國帶至法國的,河內為越戰時北越的首都,即現在的胡志明市;1883年法國數學家 Edouard ...

程式碼

#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);
    }
}
執行結果

解題重點: