汉诺塔问题「递归」

汉诺塔问题「递归」_第1张图片

 

# _*_coding:utf-8_*_
# create by TynMh 2019-05-21 21:55


def hanoi(n, a, b, c):
    if n > 0:
        hanoi(n-1, a, c, b)
        print('Moving %s to %s   %s' % (a, c, n))
        hanoi(n-1, b, a, c)


hanoi(3, 'A', 'B', 'C')

结果:

Moving A to C   1
Moving A to B   2
Moving C to B   1
Moving A to C   3
Moving B to A   1
Moving B to C   2
Moving A to C   1

递归分析:

汉诺塔问题「递归」_第2张图片

你可能感兴趣的:(Python)