漢諾塔問題:https://baike.baidu.com/item/%E6%B1%89%E8%AF%BA%E5%A1%94/3468295?fr=aladdin
思路:
先借助C將A上面n-1個盤子移到B中;然後將A上最大的盤子移到C中;再借助A將B上的n-1個盤子移動到C上。
#include<iostream>
using namespace std;
void move(char x, char y){
cout << x << "--->" << y << endl;
}
void hanoi(int n, char one, char two, char three){
if(n == 1) move(one, three);
else{
//藉助C到B
hanoi(n - 1, one, three, two);
move(one, three);
hanoi(n - 1, two, one, three);
}
}
int main(){
int n;//n表示盤子的個數
while(cin >> n){
hanoi(n, 'A', 'B', 'C');
}
return 0;
}
以上就是這篇的全部內容,如有問題請您指出,謝謝!