题解 | #用栈来求解汉诺塔问题#

用栈来求解汉诺塔问题

http://www.nowcoder.com/practice/1a2f618b3433487295657b3414f4e7c4

n = int(input())
step = 0
def move(n, fro, to):
    global step
    step += 1
    print("Move " + str(n) + " from " + fro + " to " + to)
    
def hanota(n, a, b, c):
    step = 0
    if n == 1:
        move(n, a, b)
        move(n, b, c)
    else:
        hanota(n - 1, a, b, c)
        move(n, a, b)
        hanota(n - 1, c, b, a)
        move(n, b, c)
        hanota(n - 1, a, b, c)
hanota(n, "left", "mid", "right")
print("It will move " + str(step) + " steps.")
全部评论

相关推荐

想去夏威夷的小哥哥在度假:5和6才是重点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务