汉诺塔的python递归实现
时间: 2023-12-18 21:30:12 浏览: 187
以下是汉诺塔的Python递归实现代码:
```python
i = 1
def move(pfrom, pto):
global i
print("第%d步:%s --> %s" % (i, pfrom, pto))
i += 1
def hanoi(n, a, b, c):
if n == 1:
move(a, c)
else:
hanoi(n - 1, a, c, b)
move(a, c)
hanoi(n - 1, b, a, c)
n = int(input("请输入盘数:"))
print("具体走法步骤如下:")
hanoi(n, "A", "B", "C")
print("一共需走%d步" % (i - 1))
```
相关问题
汉诺塔python递归解决
好的,以下是 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 个盘子从辅助柱子移动到目标柱子。
汉诺塔python递归函数
汉诺塔问题是一个经典的递归问题,可以使用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
```
阅读全文