Chapter 3 Stacks and Queues - 3.4

本文介绍了一个经典的递归问题——汉诺塔,并提供了一种使用堆栈实现的递归解决方案。该方案遵循汉诺塔游戏的基本规则,通过递归调用实现了盘子从初始杆到目标杆的移动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 3.4: In the classic problem of the Towers of Hanoi, you have 3 rods and N disks fo different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (e.g., each disk sits on top of an even larger one). You have the following constrains:
(A) Only one disk can be moved at a time.
(B) A disk is slid off the top of one rod onto the next rod.
(C) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first rod to the last using Stacks.


So classic, so recursive:P
from stack import *
rods = [stack(), stack(), stack()]
def Hanoi(n, rod_from, rod_to):
    if n == 2:
        Move(rod_from, 3 - (rod_from + rod_to))
        Move(rod_from, rod_to)
        Move(3 - (rod_from + rod_to), rod_to)
    else:
        Hanoi(n - 1, rod_from, 3 - (rod_from + rod_to))
        Move(rod_from, rod_to)
        Hanoi(n - 1, 3 - (rod_from + rod_to), rod_to)
def Move(rod_from, rod_to):
    print "Move from", rod_from, "to", rod_to
    rods[rod_to].push(rods[rod_from].pop())

# Test case
if __name__ == "__main__":
    # range(1, 8)[::-1] gets a reverse list
    # Sequence slicing [starting-at-index : but-less-than-index [ : step]].
    # Start defaults to 0, end to len(sequence), step to 1
    for i in range(1, 8)[::-1]:
        rods[0].push(i)
    Hanoi(7, 0, 2)
    for i in range(0, 7):
        print "rods[2].pop():", rods[2].pop()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值