用python写汉诺塔
时间: 2023-09-30 21:11:46 浏览: 38
可以使用递归函数来解决汉诺塔问题,以下是使用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 n-1 disks from auxiliary to target peg
hanoi(n-1, auxiliary, target, source)
# test the function with 3 disks
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
```
相关问题
用Python写汉诺塔问题
好的,以下是用Python实现汉诺塔问题的代码:
```python
def hanoi(n, a, b, c):
if n == 1:
print(a, "->", c)
else:
hanoi(n-1, a, c, b)
print(a, "->", c)
hanoi(n-1, b, a, c)
n = int(input("请输入汉诺塔的层数:"))
hanoi(n, 'A', 'B', 'C')
```
代码中的`hanoi`函数接受四个参数,分别为:盘子数量、起始柱子、中间柱子、目标柱子。当盘子数量为1时,直接将起始柱子上的盘子移动到目标柱子上;否则,先将n-1个盘子从起始柱子通过目标柱子移动到中间柱子上,再将起始柱子上的最后一个盘子移动到目标柱子上,最后将中间柱子上的n-1个盘子通过起始柱子移动到目标柱子上。
最后,调用`hanoi`函数并传入汉诺塔的层数和三个柱子的编号,即可输出汉诺塔的移动步骤。
用python写个汉诺塔
下面是用 Python 实现汉诺塔的代码:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# 将 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
```