用python实现使用递归函数实现汉诺塔问题
时间: 2024-01-01 20:05:46 浏览: 74
好的,汉诺塔问题是一个经典的递归问题,可以用 Python 的递归函数来解决。下面是一个示例代码:
```python
def hanoi(n, src, dst, mid):
if n == 1:
print('Move disk 1 from', src, 'to', dst)
else:
hanoi(n-1, src, mid, dst)
print('Move disk', n, 'from', src, 'to', dst)
hanoi(n-1, mid, dst, src)
# 测试代码
hanoi(3, 'A', 'C', 'B')
```
这段代码实现了将 n 个大小不同的盘子从源柱子 src 移动到目标柱子 dst 的操作,其中可以借助中间柱子 mid。递归函数 hanoi(n, src, dst, mid) 会先将 n-1 个盘子从 src 移动到 mid,再将最后一个盘子从 src 移动到 dst,最后将 n-1 个盘子从 mid 移动到 dst。
希望这个回答能够帮助你。另外,你知道吗,据说最快的汉诺塔游戏记录是用了 35 步,是由美国的两位程序员完成的。
相关问题
python实现汉诺塔递归函数
以下是Python实现汉诺塔递归函数的代码示例:
```python
def hanoi(n, source, target, auxiliary):
if n == 1:
print("Move disk 1 from", source, "to", target)
return
hanoi(n-1, source, auxiliary, target)
print("Move disk", n, "from", source, "to", target)
hanoi(n-1, auxiliary, target, source)
hanoi(3, 'A', 'C', 'B')
```
这段代码实现了一个递归函数,用于解决汉诺塔问题。在这个例子中,我们将3个圆盘从A柱移动到C柱,借助B柱作为辅助。
使用递归函数实现汉诺塔问题
下面是使用递归函数实现汉诺塔问题的 Python 代码:
```python
def hanoi(n, source, target, auxiliary):
if n == 1:
print('Move disk 1 from', source, 'to', target)
return
hanoi(n-1, source, auxiliary, target)
print('Move disk', n, 'from', source, 'to', target)
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` 表示汉诺塔的盘子数,`source` 表示起始柱子,`target` 表示目标柱子,`auxiliary` 表示辅助柱子。首先判断如果只有一个盘子,则直接从起始柱子移动到目标柱子;否则,先将前 `n-1` 个盘子从起始柱子移动到辅助柱子,再将最后一个盘子从起始柱子移动到目标柱子,最后将前 `n-1` 个盘子从辅助柱子移动到目标柱子,递归结束。