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

漢諾塔問題python

+= print count else glob int 移動 pytho mat


count = 0
def hanoi(n,src,mid,dst):
global count
if n == 1:
print("{}:{}->{}".format(1,src,dst))
count += 1
else:
hanoi(n-1,src,dst,mid)
print("{}:{}->{}".format(n, src, dst))#第n個圓盤從第src位置移動到dst位置
count += 1
hanoi(n-1,mid,src,dst)
hanoi(3,"A","B","C")
print(count)
#不顯示對應序列號圓盤的簡練寫法
def move(n, a, b, c):
if n == 1:
print(a, ‘-->‘, c)
else:
move(n-1,a,c,b)
print(a,‘-->‘,c)
move(n-1,b,a,c)
move(3,"A","B","C")

漢諾塔問題python