汉诺塔问题python

Posted on 2018-04-14 09:22  zhenshj  阅读(222)  评论(0)    收藏  举报

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")

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3