汉诺塔python递归解决
时间: 2023-06-22 08:43:37 浏览: 63
好的,以下是 Python 实现汉诺塔的递归解决方案:
```python
def hanoi(n, source, target, auxiliary):
if n == 1:
print("Move disk 1 from", source, "to", target)
else:
# 将 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
```
在递归解决方案中,当只有一个盘子时,直接将其从源柱子移动到目标柱子。当有多个盘子时,将前 n-1 个盘子从源柱子移动到辅助柱子,再将第 n 个盘子从源柱子移动到目标柱子,最后将前 n-1 个盘子从辅助柱子移动到目标柱子。
阅读全文