编写代码解决汉诺塔
以下是用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
原文地址: http://www.cveoy.top/t/topic/bfFJ 著作权归作者所有。请勿转载和采集!