---恢复内容开始---
汉诺塔的来源
相传在古印度圣庙中,有一种被称为汉诺塔(Hanoi)的游戏。该游戏是在一块铜板装置上,有三根杆(编号A、B、C),在A杆自下而上、由大到小按顺序放置64个金盘(如下图)。游戏的目标:把A杆上的金盘全部移到C杆上,并仍保持原有顺序叠好。操作规则:每次只能移动一个盘子,并且在移动过程中三根杆上都始终保持大盘在下,小盘在上,操作过程中盘子可以置于A、B、C任一杆上。
代码
n=eval(input()) 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(n,'A','B','C')
运行结果
动画代码
1 import turtle 2 3 class Stack: 4 def __init__(self): 5 self.items = [] 6 def isEmpty(self): 7 return len(self.items) == 0 8 def push(self, item): 9 self.items.append(item) 10 def pop(self): 11 return self.items.pop() 12 def peek(self): 13 if not self.isEmpty(): 14 return self.items[len(self.items) - 1] 15 def size(self): 16 return len(self.items) 17 18 def drawpole_3():#画出汉诺塔的poles 19 t = turtle.Turtle() 20 t.hideturtle() 21 def drawpole_1(k): 22 t.up() 23 t.pensize(10) 24 t.speed(100) 25 t.goto(400*(k-1), 100) 26 t.down() 27 t.goto(400*(k-1), -100) 28 t.goto(400*(k-1)-20, -100) 29 t.goto(400*(k-1)+20, -100) 30 drawpole_1(0)#画出汉诺塔的poles[0] 31 drawpole_1(1)#画出汉诺塔的poles[1] 32 drawpole_1(2)#画出汉诺塔的poles[2] 33 34 def creat_plates(n):#制造n个盘子 35 plates=[turtle.Turtle() for i in range(n)] 36 for i in range(n): 37 plates[i].up() 38 plates[i].hideturtle() 39 plates[i].shape("square") 40 plates[i].shapesize(1,8-i) 41 plates[i].goto(-400,-90+20*i) 42 plates[i].showturtle() 43 return plates 44 45 def pole_stack():#制造poles的栈 46 poles=[Stack() for i in range(3)] 47 return poles 48 49 def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子plates[mov]从poles[fp]移到poles[tp] 50 mov=poles[fp].peek() 51 plates[mov].goto((fp-1)*400,150) 52 plates[mov].goto((tp-1)*400,150) 53 l=poles[tp].size()#确定移动到底部的高度(恰好放在原来最上面的盘子上面) 54 plates[mov].goto((tp-1)*400,-90+20*l) 55 56 def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子 57 if height >= 1: 58 moveTower(plates,poles,height-1,fromPole,withPole,toPole) 59 moveDisk(plates,poles,fromPole,toPole) 60 poles[toPole].push(poles[fromPole].pop()) 61 moveTower(plates,poles,height-1,withPole,toPole,fromPole) 62 63 myscreen=turtle.Screen() 64 drawpole_3() 65 n=int(input("请输入汉诺塔的层数并回车: ")) 66 plates=creat_plates(n) 67 poles=pole_stack() 68 for i in range(n): 69 poles[0].push(i) 70 moveTower(plates,poles,n,0,2,1) 71 myscreen.exitonclick()
动画示意图
---恢复内容结束---