汉诺塔python递归函数
时间: 2023-11-20 18:59:39 浏览: 105
汉诺塔问题是一个经典的递归问题,可以使用Python递归函数来解决。下面是一个示例代码:
```python
def hanoi(n, source, target, auxiliary):
if n == 1:
print("Move disk 1 from source", source, "to target", target)
return
hanoi(n-1, source, auxiliary, target)
print("Move disk", n, "from source", source, "to target", target)
hanoi(n-1, auxiliary, target, source)
# 示例调用
hanoi(3, 'A', 'C', 'B')
```
上述代码中,`hanoi`函数接受四个参数:`n`表示盘子的数量,`source`表示源柱子,`target`表示目标柱子,`auxiliary`表示辅助柱子。当`n`等于1时,直接将盘子从源柱子移动到目标柱子;否则,先将`n-1`个盘子从源柱子移动到辅助柱子,再将第`n`个盘子从源柱子移动到目标柱子,最后将`n-1`个盘子从辅助柱子移动到目标柱子。
示例调用中,我们将3个盘子从柱子A移动到柱子C,使用柱子B作为辅助柱子。运行结果如下:
```
Move disk 1 from source A to target C
Move disk 2 from source A to target B
Move disk 1 from source C to target B
Move disk 3 from source A to target C
Move disk 1 from source B to target A
Move disk 2 from source B to target C
Move disk 1 from source A to target C
```
阅读全文