python3实现数据结构与算法30天-汉诺塔与递归(1)

汉诺塔问题的实现,n个大小塔片,ABC左至右依次排布3根柱子,n=64,
开始塔片按小到大,依次高低垒在A柱,要求将塔片全部按原顺序全部堆在C柱
要求,每次只能移动一张塔片

注:如果每移动一块需要1秒,全部实现(2^64-1),大约5800亿年才能实现

思想:

  • 1.总体可以分为(n-1)部分,第n块
  • 2.先把(n-1)块移动到B柱,
  • 3.然后把第n块从A移动到C柱
  • 4.最后把B柱的(n-1)块移动到C柱

代码实现:

def hanoi(n, a, b, c): # n块塔片从a经b最后移动到c
    if n>0:
        hanoi(n-1, a, c, b) # (n-1)块塔片从a经c最后移动到b
        print("moving from %s to %s" % (a, c)) 
        hanoi(n-1, b, a, c) # (n-1)块塔片从b经a最后移动到c

if __name__ == "__main__":
    print("n=1...")
    hanoi(1, 'A', 'B', 'C')
    print("n=2...")
    hanoi(2, 'A', 'B', 'C')
    print("n=3...")
    hanoi(3, 'A', 'B', 'C')

运算结果:

n=1...
moving from A to C
n=2...
moving from A to B
moving from A to C
moving from B to C
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
原文地址:https://www.cnblogs.com/davis12/p/14530773.html