1 Count = 0 2 def hanoi(n, src, dst, mid): 3 global Count 4 if n == 1: 5 print("{}:{}->{}".format(1, src, dst)) 6 Count += 1 7 else: 8 hanoi(n-1, src, mid, dst) 9 print("{}:{}->{}".format(n, src, dst)) 10 Count += 1 11 hanoi(n-1, mid, dst, src) 12 n = eval(input('请输入汉诺塔的层数并回车:')) 13 hanoi(n, 'A', 'B', 'C') 14 print('移动共需要{}步'.format(Count))
输出: