用Python编写函数Hannoi(),要求用递归的方式实现汉诺塔(Hannoi)问题,A、B、C分别表示三根柱子,Hannoi(A,B,C,N): 表示将N个圆盘从A柱上借助B柱移动到C柱上。 格式输入1: 3 格式输出1: move: A -> C move: A -> B move: C -> B move: A -> C move: B -> A move: B -> C move: A -> C
时间: 2023-12-10 22:36:53 浏览: 120
以下是实现汉诺塔问题的Python代码:
```python
def Hannoi(A, B, C, N):
if N == 1:
print("move:", A, "->", C)
else:
Hannoi(A, C, B, N-1)
print("move:", A, "->", C)
Hannoi(B, A, C, N-1)
# 测试
n = int(input())
Hannoi('A', 'B', 'C', n)
```
运行结果:
```
3
move: A -> C
move: A -> B
move: C -> B
move: A -> C
move: B -> A
move: B -> C
move: A -> C
```
阅读全文