汉诺塔问题简介
汉诺塔问题是一个经典的问题。汉诺塔(Hanoi Tower),又称河内塔,源于印度一个古老传说。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,任何时候,在小圆盘上都不能放大圆盘,且在三根柱子之间一次只能移动一个圆盘。问应该如何操作?
汉诺塔问题移动思路
汉诺塔问题是典型的递归问题
(1) 首先将n-1个圆盘从A,经过C,移动到B
(2) 然后将第n个圆盘从A移动到C
(3) 然后再将n-1个圆盘从B,经过A,移动到C
经过如上三个步骤即可完成汉诺塔问题的移动
汉诺塔问题动画演示
汉诺塔问题代码实现
def hanoi(n,a,b,c):
"""
把n个盘子从a经过b移动到c
:param n:
:param a:
:param b:
:param c:
:return:
"""
if n>0:
hanoi(n-1,a,c,b)
print(f"moving from {a} to {c}")
hanoi(n-1,b,a,c)
if __name__=="__main__":
print("当n为3时,移动步骤:")
hanoi(3,"A","B","C")
print("当n为5时,移动步骤:")
hanoi(5, "A", "B", "C")
汉诺塔问题当n为3和5时执行结果
当n为3时,移动步骤:
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C
当n为5时,移动步骤:
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C
moving from A to B
moving from C to B
moving from C to A
moving from B to A
moving from C to B
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C
moving from B to A
moving from C to B
moving from C to A
moving from B to A
moving from B to C
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C