汉诺塔Hanoi问题的python解法

def hanoi(n, a, b, c):
    '''

    :param n: 移动圆盘的数目
    :param a: 起始柱
    :param b: 过渡柱
    :param c: 目标柱
    :return:
    '''
    if n == 1:
        print('move plate 1-st from {}->{}'.format(a, c))
        return
    else:
        hanoi(n - 1, a, c, b)
        print('move plate {}-cd from {}->{}'.format(n, a, c))
        hanoi(n - 1, b, a, c)


hanoi(3, 'a', 'b', 'c')

输出:

move plate 1-st from a->c
move plate 2-cd from a->b
move plate 1-st from c->b
move plate 3-cd from a->c
move plate 1-st from b->a
move plate 2-cd from b->c
move plate 1-st from a->c

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。