python汉诺塔编程代码

汉诺塔问题是一个经典的递归问题。以下是使用Python实现汉诺塔的一个简单方法:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# 把 n-1 个盘子从 source 移动到 auxiliary
hanoi(n-1, source, auxiliary, target)

# 把第 n 个盘子从 source 移动到 target
print(f"把第 {n} 个盘子从 {source} 移动到 {target}")

# 把 n-1 个盘子从 auxiliary 移动到 target
hanoi(n-1, auxiliary, target, source)
# 测试
hanoi(3, "A", "C", "B")
```
这个程序定义了一个名为 `hanoi` 的函数,它接受四个参数:盘子的数量(n)、源柱子(source)、目标柱子(target)和辅助柱子(auxiliary)。通过递归调用 `hanoi` 函数,我们可以实现汉诺塔问题的求解。在测试中,我们使用3个盘子,源柱子为A,目标柱子为C,辅助柱子为B。

以下是Python实现汉诺塔的代码:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# 将n-1个盘子从源柱移动到辅助柱
hanoi(n-1, source, auxiliary, target)
# 将第n个盘子从源柱移动到目标柱
print("Move disk", n, "from", source, "to", 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

猜你喜欢

转载自blog.csdn.net/qq_42751978/article/details/130695135