汉诺塔递归错解,想知道错误原因在哪儿
#我把每个柱子上盘子当作一个stack,hanoi(s1,s2,s3)就是把stack1里的通过stack2移动到stack3里。
# hanoi(s1[1:],s3,s2) 是把stack1除了第一层的盘子通过stack3移动到stack2
def hanoi(s1,s2,s3):
h = len(s1)
if h >= 1:
hanoi(s1[1:],s3,s2)
s3.append(s1.pop())
hanoi(s2,s1,s3)
print(f"{s1}{s2}{s3}")
运行结果及报错内容
为什么我这个想法实现不了呢,哪里出错了呢
i = 1
def move(pfrom, pto):
global i
print("第%d步:%s ---> %s" % (i, pfrom, pto))
i += 1
def hanoi(n, a, b, c):
if n == 1:
move(a, c)
else:
hanoi(n - 1, a, c, b)
move(a, c)
hanoi(n - 1, b, a, c)
n = int(input("请输入盘数:"))
print("具体走法步骤如下:")
hanoi(n, "A", "B", "C")
print("一共需走%d步" % (i - 1))