河内塔的Python程序
河内塔是一个数学难题,我们有三个杆和 n 个圆盘。谜题的目标是将整个堆栈移动到另一根杆上,遵循以下简单规则:
1) 一次只能移动一个磁盘。
2) 每次移动都包括从其中一个堆栈中取出上面的磁盘并将其放在另一个堆栈的顶部,即只有当磁盘是堆栈中最上面的磁盘时才能移动磁盘。
3) 任何磁盘都不能放在较小的磁盘上。
注意:将前 n-1 个圆盘从源棒转移到辅助棒可以再次被认为是一个新问题,可以用同样的方式解决。
Python3
# Recursive Python function to solve the tower of hanoi
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
# Driver code
n = 4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
# Contributed By Dilip Jain
输出
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Move disk 3 from source A to destination C
Move disk 1 from source B to destination A
Move disk 2 from source B to destination C
Move disk 1 from source A to destination C
Move disk 4 from source A to destination B
Move disk 1 from source C to destination B
Move disk 2 from source C to destination A
Move disk 1 from source B to destination A
Move disk 3 from source C to destination B
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
详情请参阅完整的河内塔计划文章!