用linuxc编写汉诺塔程序
时间: 2024-05-16 15:16:11 浏览: 12
以下是一个用 C 语言编写的汉诺塔程序,可以在 Linux 系统下运行:
```c
#include <stdio.h>
void move(int n, char a, char b, char c);
int main() {
int n;
printf("请输入盘子的数量:");
scanf("%d", &n);
printf("移动步骤如下:\n");
move(n, 'A', 'B', 'C');
return 0;
}
void move(int n, char a, char b, char c) {
if (n == 1) {
printf("%c -> %c\n", a, c);
} else {
move(n - 1, a, c, b);
printf("%c -> %c\n", a, c);
move(n - 1, b, a, c);
}
}
```
使用方法:
1. 打开终端,进入程序所在的目录。
2. 输入 `gcc -o hanoi hanoi.c` 进行编译,生成可执行文件 `hanoi`。
3. 输入 `./hanoi` 执行程序,根据提示输入盘子的数量即可。
程序会输出移动盘子的步骤。其中,`A`、`B`、`C` 分别代表三个柱子,`n` 代表盘子的数量。
相关问题
用python编写汉诺塔程序
好的,以下是用 Python 编写汉诺塔程序的示例代码:
```python
def hanoi(n, source, target, auxiliary):
# 当只剩下一个盘子时,直接将其从源柱移动到目标柱
if n == 1:
print("Move disk 1 from {} to {}".format(source, target))
return
# 将 n - 1 个盘子从源柱移动到辅助柱
hanoi(n-1, source, auxiliary, target)
# 将第 n 个盘子从源柱移动到目标柱
print("Move disk {} from {} to {}".format(n, source, target))
# 将 n - 1 个盘子从辅助柱移动到目标柱
hanoi(n-1, auxiliary, target, source)
# 测试代码
hanoi(3, "A", "C", "B")
```
输出结果:
```
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
```
在示例代码中,`n` 表示盘子的数量,`source`、`target` 和 `auxiliary` 分别表示源柱、目标柱和辅助柱。在函数中,我们使用递归的方式将盘子从源柱移动到目标柱,具体实现方式请参考代码注释。
python编写汉诺塔程序
以下是Python实现汉诺塔问题的代码:
```python
def hanoi(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
hanoi(n-1, a, c, b)
print(a, '-->', c)
hanoi(n-1, b, a, c)
n = int(input('请输入汉诺塔的层数:'))
hanoi(n, 'A', 'B', 'C')
```
运行程序后,输入汉诺塔的层数,程序将会输出汉诺塔移动的步骤。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)