1. 程式人生 > >漢諾塔問題--python實現

漢諾塔問題--python實現

漢諾塔問題–python實現 自定義盤子數目,實現詳細過程分析

def han(num,src,dst,step):
    global times
    if num==1:
        times+=1
        print('The {} times move is {} to {}'.format(times,src,dst))
        towers[dst].append(towers[src].pop())
        for tower in 'ABC':
            print(tower,':',towers[tower])
    else:
        han(num-1,src,step,dst)
        han(1,src,dst,step)
        han(num-1,step,dst,src)
n=int(input('請輸入金盤數目:'))
towers={'A':list(range(n,0,-1)),
        'B':[],
        'C':[]
        }
times=0
han(n,'A','B','C')

執行結果: 請輸入金盤數目:5 The 1 times move is A to B A : [5, 4, 3, 2] B : [1] C : [] The 2 times move is A to C A : [5, 4, 3] B : [1] C : [2] The 3 times move is B to C A : [5, 4, 3] B : [] C : [2, 1] The 4 times move is A to B A : [5, 4] B : [3] C : [2, 1] The 5 times move is C to A A : [5, 4, 1] B : [3] C : [2] The 6 times move is C to B A : [5, 4, 1] B : [3, 2] C : [] The 7 times move is A to B A : [5, 4] B : [3, 2, 1] C : [] The 8 times move is A to C A : [5] B : [3, 2, 1] C : [4] The 9 times move is B to C A : [5] B : [3, 2] C : [4, 1] The 10 times move is B to A A : [5, 2] B : [3] C : [4, 1] The 11 times move is C to A A : [5, 2, 1] B : [3] C : [4] The 12 times move is B to C A : [5, 2, 1] B : [] C : [4, 3] The 13 times move is A to B A : [5, 2] B : [1] C : [4, 3] The 14 times move is A to C A : [5] B : [1] C : [4, 3, 2] The 15 times move is B to C A : [5] B : [] C : [4, 3, 2, 1] The 16 times move is A to B A : [] B : [5] C : [4, 3, 2, 1] The 17 times move is C to A A : [1] B : [5] C : [4, 3, 2] The 18 times move is C to B A : [1] B : [5, 2] C : [4, 3] The 19 times move is A to B A : [] B : [5, 2, 1] C : [4, 3] The 20 times move is C to A A : [3] B : [5, 2, 1] C : [4] The 21 times move is B to C A : [3] B : [5, 2] C : [4, 1] The 22 times move is B to A A : [3, 2] B : [5] C : [4, 1] The 23 times move is C to A A : [3, 2, 1] B : [5] C : [4] The 24 times move is C to B A : [3, 2, 1] B : [5, 4] C : [] The 25 times move is A to B A : [3, 2] B : [5, 4, 1] C : [] The 26 times move is A to C A : [3] B : [5, 4, 1] C : [2] The 27 times move is B to C A : [3] B : [5, 4] C : [2, 1] The 28 times move is A to B A : [] B : [5, 4, 3] C : [2, 1] The 29 times move is C to A A : [1] B : [5, 4, 3] C : [2] The 30 times move is C to B A : [1] B : [5, 4, 3, 2] C : [] The 31 times move is A to B A : [] B : [5, 4, 3, 2, 1] C : []