以下是用 Python 编写的汉诺塔问题解决代码:

def hanoi(n, source, target, auxiliary):
    if n > 0:
        # 将n-1个盘子从source移动到auxiliary
        hanoi(n-1, source, auxiliary, target)
        # 将第n个盘子从source移动到target
        print('Move disk', n, 'from', source, 'to', target)
        # 将n-1个盘子从auxiliary移动到target
        hanoi(n-1, auxiliary, target, source)

# 测试代码
hanoi(3, 'A', 'C', 'B')

# 输出结果
# Move disk 1 from A to C
# Move disk 2 from A to B
# Move disk 1 from C to B
# Move disk 3 from A to C
# Move disk 1 from B to A
# Move disk 2 from B to C
# Move disk 1 from A to C

代码解释:

  1. 函数定义: hanoi(n, source, target, auxiliary) 函数用于解决汉诺塔问题。
    • n: 需要移动的盘子数量
    • source: 源柱子
    • target: 目标柱子
    • auxiliary: 辅助柱子
  2. 递归逻辑: 代码利用递归函数来实现汉诺塔问题的解决。
    • 首先,递归调用 hanoi 函数,将 n-1 个盘子从 source 移动到 auxiliary 柱子,使用 target 作为辅助柱子。
    • 然后,将最大的盘子 (n) 从 source 移动到 target 柱子。
    • 最后,再次递归调用 hanoi 函数,将 n-1 个盘子从 auxiliary 移动到 target 柱子,使用 source 作为辅助柱子。
  3. 测试代码: hanoi(3, 'A', 'C', 'B') 用于测试代码,移动 3 个盘子,源柱子为 'A',目标柱子为 'C',辅助柱子为 'B'。

该代码演示了汉诺塔问题的一种经典的递归解决方法,并展示了其运行结果。

Python 实现汉诺塔问题:代码详解与演示

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

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