码迷,mamicode.com
首页 > 编程语言 > 详细

Python汉诺塔问题

时间:2020-03-30 23:46:33      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:可视化   int   append   pre   else   class   move   details   一个   

实现和线上汉诺塔移动问题

def hannuo(n,a,b,c):
    if n == 1:
        print(a,"->",c)
    else:
        hannuo(n-1,a,c,b)#将最后一个盘子移到c
        print(a,"->",c)#将剩余的盘子移动c 
        hannuo(n-1,b,a,c)
n = int(input())
hannuo(n,"A","B","C")

汉诺塔问题可视化

#(参考修改于https://blog.csdn.net/weixin_44046046/article/details/88858031)
import turtle
turtle.setup(width=0.99, height=0.99)
class Stack:
    def __init__(self):
       self.items = []
    def isEmpty(self):
        return len(self.items) == 0
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        if not self.isEmpty():
            return self.items[len(self.items) - 1]
    def size(self):
        return len(self.items)
turtle.done
def drawpole_3():
    t = turtle.Turtle()
    t.hideturtle()
    def drawpole_1(k):
        t.up()
        t.pensize(10)
        t.speed(100)
        t.goto(400*(k-1), 300)
        t.down()
        t.goto(400*(k-1), -100)
        t.goto(400*(k-1)-20, -100)
        t.goto(400*(k-1)+20, -100)
    drawpole_1(0)
    drawpole_1(1)
    drawpole_1(2)
def creat_plates(n):
    plates=[turtle.Turtle() for i in range(n)]
    for i in range(n):
        plates[i].up()
        plates[i].hideturtle()
        plates[i].shape("square")
        plates[i].shapesize(1,20-i)
        plates[i].goto(-400,-90+20*i)
        plates[i].showturtle()
    return plates
def pole_stack():
    poles=[Stack() for i in range(3)]
    return poles
def moveDisk(plates,poles,fp,tp):
    mov=poles[fp].peek()
    plates[mov].goto((fp-1)*400,300)
    plates[mov].goto((tp-1)*400,300)
    l=poles[tp].size()
    plates[mov].goto((tp-1)*400,-90+20*l)
def moveTower(plates,poles,height,fromPole, toPole, withPole): 
    if height >= 1:
        moveTower(plates,poles,height-1,fromPole,withPole,toPole)
        moveDisk(plates,poles,fromPole,toPole)
        poles[toPole].push(poles[fromPole].pop())
        moveTower(plates,poles,height-1,withPole,toPole,fromPole)
myscreen=turtle.Screen()
drawpole_3()
n=3
plates=creat_plates(n)
poles=pole_stack()
for i in range(n):
    poles[0].push(i)
moveTower(plates,poles,n,0,2,1)
myscreen.exitonclick()

 

Python汉诺塔问题

标签:可视化   int   append   pre   else   class   move   details   一个   

原文地址:https://www.cnblogs.com/linjiaxin59/p/12601852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!