defhanoi(n, a, b, c, depth=0): defmove(n, a, c): global step print(" " * depth, end="") print(f"{step=}: move [{n}] from {a} to {c}") step += 1
if n == 1: move(n, a, c) else: hanoi(n - 1, a, c, b, depth=depth + 1) move(n, a, c) hanoi(n - 1, b, a, c, depth=depth + 1)
if __name__ == "__main__": n = int(input("Hanoi Problem, N = ")) hanoi(n, "A", "B", "C")
这里可以记录步数,并且通过缩进的不同展示了递归的关系。例如N=4的结果如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Hanoi Problem, N = 4 step=1: move [1] from A to B step=2: move [2] from A to C step=3: move [1] from B to C step=4: move [3] from A to B step=5: move [1] from C to A step=6: move [2] from C to B step=7: move [1] from A to B step=8: move [4] from A to C step=9: move [1] from B to C step=10: move [2] from B to A step=11: move [1] from C to A step=12: move [3] from B to C step=13: move [1] from A to B step=14: move [2] from A to C step=15: move [1] from B to C
step=1: move [1] from A to B step=2: move [2] from A to C step=3: move [1] from B to C step=4: move [3] from A to B step=5: move [1] from C to A step=6: move [2] from C to B step=7: move [1] from A to B step=8: move [4] from A to C step=9: move [1] from B to C step=10: move [2] from B to A step=11: move [1] from C to A step=12: move [3] from B to C step=13: move [1] from A to B step=14: move [2] from A to C step=15: move [1] from B to C
step=1 move [1] from A to B step=2 move [2] from A to C step=3 move [1] from B to C step=4 move [3] from A to B step=5 move [1] from C to A step=6 move [2] from C to B step=7 move [1] from A to B step=8 move [4] from A to C step=9 move [1] from B to C step=10 move [2] from B to A step=11 move [1] from C to A step=12 move [3] from B to C step=13 move [1] from A to B step=14 move [2] from A to C step=15 move [1] from B to C