hanoi问题代码实现
时间: 2023-09-27 14:08:17 浏览: 50
以下是Hanoi问题的Python代码实现:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# Move n-1 disks from source to auxiliary peg
hanoi(n-1, source, auxiliary, target)
# Move the nth disk from source to target peg
print("Move disk", n, "from", source, "to", target)
# Move the n-1 disks from auxiliary to target peg
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
```
该代码使用递归实现了Hanoi问题的解决方案。函数hanoi(n, source, target, auxiliary)接收三个参数:n表示要移动的盘子数量,source表示源柱子的名称,target表示目标柱子的名称,auxiliary表示辅助柱子的名称。
在函数中,首先检查是否有需要移动的盘子。如果有,它会递归地调用hanoi函数,以将前n-1个盘子从源柱子移动到辅助柱子。然后,它将第n个盘子从源柱子移动到目标柱子。最后,它再次递归地调用hanoi函数,将前n-1个盘子从辅助柱子移动到目标柱子。