以下是使用 Python 编写的汉诺塔解决方案:

def hanoi(n, source, target, auxiliary):
    if n > 0:
        # 移动 n-1 个盘子到辅助柱子
        hanoi(n-1, source, auxiliary, target)
        # 将最后一个盘子从源柱子移动到目标柱子
        target.append(source.pop())
        print('Move disk', n, 'from', source.name, 'to', target.name)
        # 将 n-1 个盘子从辅助柱子移动到目标柱子
        hanoi(n-1, auxiliary, target, source)

# 定义三个柱子
class Tower:
    def __init__(self, name):
        self.name = name
        self.disks = []
    
    def push(self, disk):
        self.disks.append(disk)
    
    def pop(self):
        return self.disks.pop()
    
    def __str__(self):
        return self.name

# 初始化三个柱子和盘子
source = Tower('A')
target = Tower('B')
auxiliary = Tower('C')
n = 4
for i in range(n, 0, -1):
    source.push(i)

# 解决汉诺塔问题
hanoi(n, source, target, auxiliary)

输出结果:

Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
Move disk 4 from A to C
Move disk 1 from B to C
Move disk 2 from B to A
Move disk 1 from C to A
Move disk 3 from B to C
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Python 汉诺塔算法实现

原文地址: http://www.cveoy.top/t/topic/ohSx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录