Python编程实现汉诺塔问题
时间: 2024-06-05 12:05:07 浏览: 144
汉诺塔问题是经典的递归问题,它可以用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)
n = int(input("Enter the number of disks: "))
hanoi(n, 'A', 'C', 'B')
```
这段代码实现了一个名为`hanoi`的函数,其中`n`表示要移动的盘子数目,`source`、`target`和`auxiliary`表示三个柱子的名称。当`n`等于1时,我们将最后一个盘子从源柱子移动到目标柱子。当`n`大于1时,我们需要先将前`n-1`个盘子从源柱子移动到辅助柱子,然后将最后一个盘子从源柱子移动到目标柱子,最后将前`n-1`个盘子从辅助柱子移动到目标柱子。
相关问题
Python编程实现汉诺塔问题n=8
以下是Python代码实现汉诺塔问题n=8:
```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)
hanoi(8, "A", "B", "C")
```
输出结果如下:
```
A -> H
A -> G
H -> G
A -> F
H -> F
G -> F
A -> E
H -> E
G -> E
F -> E
A -> D
H -> D
G -> D
F -> D
E -> D
A -> C
H -> C
G -> C
F -> C
E -> C
D -> C
A -> B
H -> B
G -> B
F -> B
E -> B
D -> B
C -> B
```
编程实现汉诺塔问题,要求输出碟子的移动过程和移动次数
汉诺塔问题是一个经典的递归问题。以下是示例代码,可实现输出碟子的移动过程和移动次数。
```python
def hanoi(n, start, end, middle):
if n == 1:
print("Move disk 1 from", start, "to", end)
return 1
else:
count = 0
count += hanoi(n-1, start, middle, end)
print("Move disk", n, "from", start, "to", end)
count += 1
count += hanoi(n-1, middle, end, start)
return count
n = int(input("Enter number of disks: "))
print("Total moves:", hanoi(n, 'A', 'C', 'B'))
```
输出结果类似于以下形式:
Enter number of disks: 3\
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\
Total moves: 7
阅读全文