汉诺塔问题: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;
}
以上就是这篇的全部内容,如有问题请您指出,谢谢!