递归实现
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')
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)