汉诺塔C++程序代码
时间: 2024-10-12 19:02:00 浏览: 39
四柱汉诺塔c++源代码
汉诺塔的C++程序代码通常采用递归的方式编写,这里提供一个简单的例子:
```cpp
#include <iostream>
using namespace std;
void hanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl;
return;
}
hanoi(n-1, from_rod, aux_rod, to_rod); // Move n-1 disks from A to B
cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;
hanoi(n-1, aux_rod, to_rod, from_rod); // Move n-1 disks from B to C
}
int main() {
int num_disks; // Number of disks
cout << "Enter the number of disks: ";
cin >> num_disks;
hanoi(num_disks, 'A', 'C', 'B'); // Starting with A as source, C as destination, and B as auxiliary
return 0;
}
```
在这个代码中,`hanoi`函数负责递归实现汉诺塔游戏,输入的是盘子数`n`和三个杆子名称。当你运行此程序并输入盘子数量,它会按照规则逐步移动每个盘子。
阅读全文