問題
有三個立柱A、B、C。A柱上穿有大小不等的圓盤N個,較大的圓盤在下,較小的圓盤在上。要求把A柱上的圓盤全部移到C柱上,保持大盤在下、小盤在上的規律(可藉助B柱)。每次移動只能把一個柱子最上面的圓盤移到另一個柱子的最上面。請輸出移動過程。
解答
這是動態規劃問題中的一種,用遞歸來實現較爲簡單方便。
對於“將moveSum個圓盤從from柱移動到to柱(藉助by柱)”這個問題,我們可以通過以下三步實現:
1. 將from柱最上面的moveSum-1個圓盤移動到by柱(藉助to柱)
2. 將from柱上剩下的那1個圓盤直接移動到to柱
3. 將by柱上的moveSum-1個圓盤移動到to柱(藉助from柱)
圖示
代碼
nclude <iostream>
using namespace std;
const int sumOfPlates = 4;
int sum[3] = { sumOfPlates, 0, 0 };
enum pillar{ A, B, C };
char name[3] = { 'A', 'B', 'C' };
void move(int moveSum, pillar from, pillar by, pillar to);
void main(){
move(sumOfPlates, A, B, C);
}
void move(int moveSum, pillar from, pillar by, pillar to){
if (moveSum == 0){
return;
}
else{
move(moveSum - 1, from, to, by);
cout << "move uppermost plate from " << name[from] << " to " << name[to] << endl;
move(moveSum - 1, by, from, to);
}
}