汉诺塔的递归与非递归(python代码实现)

递归实现

def hanoi(n, a, b, c):
    if n == 1:
        print(a + '--->' + c)
    else:
        hanoi(n-1, a, c, b)
        print(a + '--->' + c)
        hanoi(n-1, b, a, c)

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

汉诺塔的递归与非递归(python代码实现)_第1张图片
非递归实现

def hanoi(n):
    tower_belong = [0] * n
    if n % 2 == 0:
        tower_name = ['A', 'B', 'C']
    else:
        tower_name = ['A', 'C', 'B']
    for step in range(1, 2 ** n):
        bin_step = bin(step)
        gold_num = len(bin_step) - bin_step.rfind('1') - 1

        print(f"第 {step:2} 步:移动 {str(gold_num)} 号金片,从 {tower_name[tower_belong[gold_num]]} 塔到", end=' ')
        if gold_num % 2 == 0:
            tower_belong[gold_num] = (tower_belong[gold_num] + 1) % 3
        else:
            tower_belong[gold_num] = (tower_belong[gold_num] + 2) % 3
        print(tower_name[tower_belong[gold_num]], '塔')

hanoi(3)

汉诺塔的递归与非递归(python代码实现)_第2张图片

你可能感兴趣的:(IT杂文,python,算法练习)