汉诺塔游戏制作C语言
时间: 2024-12-31 21:14:50 浏览: 13
### 关于C语言实现汉诺塔游戏
#### 汉诺塔问题简介
汉诺塔问题是典型的递归问题之一,其核心在于通过递归来解决问题。具体来说,在给定三个柱子的情况下,目标是从起始柱将所有不同大小的圆盘按照特定规则移动到目标柱上[^1]。
#### 完整代码示例
下面展示了一个完整的C语言程序来模拟并解决汉诺塔问题:
```c
#include <stdio.h>
int count;
void move(char fromPeg, char toPeg, int diskNumber) {
printf("Move disk %d from peg %c to peg %c\n", diskNumber, fromPeg, toPeg);
count++;
}
void hanoiTower(char sourcePeg, char auxiliaryPeg, char targetPeg, int numberOfDisks) {
if (numberOfDisks == 1) {
move(sourcePeg, targetPeg, numberOfDisks);
} else {
// Move n-1 disks from the source peg to the auxiliary peg using the target as temporary storage.
hanoiTower(sourcePeg, targetPeg, auxiliaryPeg, numberOfDisks - 1);
// Move remaining single largest disk directly from source to target peg.
move(sourcePeg, targetPeg, numberOfDisks);
// Finally, move those previously moved n-1 disks now located on auxiliary back onto final destination at target peg.
hanoiTower(auxiliaryPeg, sourcePeg, targetPeg, numberOfDisks - 1);
}
}
int main() {
int num;
printf("Enter number of disks: ");
scanf("%d", &num);
// Call function with initial parameters representing three poles labeled 'A', 'B' and 'C'.
hanoiTower('A', 'B', 'C', num);
printf("\nTotal moves required were: %d\n", count);
return 0;
}
```
此段代码实现了基本功能,即接收用户输入表示初始状态下的圆盘数量,并调用`hanoiTower()`函数完成整个转移操作;每一步骤都会打印出来以便观察执行流程[^2]。
阅读全文