c++有三根标为A,B,C的柱子,A柱子上从上到下按金字塔状依次叠放着n个半径从1厘米到n厘米的的圆盘,要把A上的所有盘子移动到柱子C上,中间可以临时放在B上,但每次移动每一根柱子上都不能出现大盘子在小盘子上方的情况,要求用最少的移动次数完成,请编程模拟每次移动。
时间: 2024-03-16 09:41:18 浏览: 22
好的,这是一个经典的汉诺塔问题,可以使用递归算法来解决。以下是C++代码实现:
```
#include <iostream>
using namespace std;
void move(int n, char from, char to, char temp) {
if (n == 1) {
cout << "Move disk " << n << " from " << from << " to " << to << endl;
}
else {
move(n - 1, from, temp, to);
cout << "Move disk " << n << " from " << from << " to " << to << endl;
move(n - 1, temp, to, from);
}
}
int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;
move(n, 'A', 'C', 'B');
return 0;
}
```
在这个程序中,`move`函数用于移动圆盘。当只有一个圆盘时,直接将它从 `from` 柱子移动到 `to` 柱子;当有多个圆盘时,将前 n-1 个圆盘从 `from` 柱子移动到 `temp` 柱子,然后将第 n 个圆盘从 `from` 柱子移动到 `to` 柱子,最后将前 n-1 个圆盘从 `temp` 柱子移动到 `to` 柱子。在主程序中,读入圆盘的数量 n,然后调用 `move` 函数进行移动。