py_递归实例:汉诺塔问题

递归的两个特点

  • 调用自身
  • 结束条件
# _*_coding:utf-8
'''
递归实例:汉诺塔问题
n----盘子总数
a----第一个柱子
b----第二个柱子
c----第三个柱子
n个盘子时:
    1、将n-1个盘子,从A经过C移动到B
    2、把n-1个盘子,从A移动到C
    3、把n-1个盘子,从B经过A移动到C
'''
#a,b,c  从a开始,经过b,移动到c
def hanoi(n,a,b,c):
    if n>0:
        hanoi(n-1,a,c,b)
        print("moving from %s to %s" %(a,c) )
        hanoi(n-1,b,a,c)
hanoi(3,"A","B","C")

'''
ps
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/c-jw/p/12564410.html