1,要求实现和线上移动汉诺塔过程
代码如下:
1 def hanoi(n, a, b, c): 2 if n == 1: 3 print(a, '-->', c) 4 else: 5 hanoi(n - 1, a, c, b) 6 print(a, '-->', c) 7 hanoi(n - 1, b, a, c) 8 # 调用 9 hanoi(5, 'A', 'B', 'C')
结果如下:
但是为了更好地看出汉诺塔的移动过程,我利用了python中的turtle进行绘制
2,用动画实现汉诺塔过程
代码如下:
1 def creat_plates(n):#制造n个盘子 2 plates=[turtle.Turtle() for i in range(n)] 3 for i in range(n): 4 plates[i].up() 5 plates[i].hideturtle() 6 plates[i].shape("square") 7 plates[i].shapesize(1,8-i) 8 plates[i].goto(-400,-90+20*i) 9 plates[i].showturtle() 10 return plates 11 12 def pole_stack():#制造poles的栈 13 poles=[Stack() for i in range(3)] 14 return poles 15 16 def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子plates[mov]从poles[fp]移到poles[tp] 17 mov=poles[fp].peek() 18 plates[mov].goto((fp-1)*400,150) 19 plates[mov].goto((tp-1)*400,150) 20 l=poles[tp].size()#确定移动到底部的高度(恰好放在原来最上面的盘子上面) 21 plates[mov].goto((tp-1)*400,-90+20*l) 22 23 def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子 24 if height >= 1: 25 moveTower(plates,poles,height-1,fromPole,withPole,toPole) 26 moveDisk(plates,poles,fromPole,toPole) 27 poles[toPole].push(poles[fromPole].pop()) 28 moveTower(plates,poles,height-1,withPole,toPole,fromPole) 29 30 myscreen=turtle.Screen() 31 drawpole_3() 32 n=int(input("请输入汉诺塔的层数并回车: ")) 33 plates=creat_plates(n) 34 poles=pole_stack() 35 for i in range(n): 36 poles[0].push(i) 37 moveTower(plates,poles,n,0,2,1) 38 myscreen.exitonclick()
结果如下: