利用递归解决“汉诺塔的移动”问题(使用python来做的,其它语言也行)

时间:2021-04-08 16:48:05

有a,b,c三个柱子,n个盘子。

def move(n, a, b, c):

  if n == 1:

    print('move', a, '-->', c)

  else:

    move(n-1, a, c, b)

    move(1, a, b, c)

    move(n-1, b, a, c)

move(5, 'A', 'B', 'C')

执行结果为:

=== RESTART: C:/Users/0923/AppData/Local/Programs/Python/Python37/test.py ===
move A --> C
move A --> B
move C --> B
move A --> C
move B --> A
move B --> C
move A --> C
move A --> B
move C --> B
move C --> A
move B --> A
move C --> B
move A --> C
move A --> B
move C --> B
move A --> C
move B --> A
move B --> C
move A --> C
move B --> A
move C --> B
move C --> A
move B --> A
move B --> C
move A --> C
move A --> B
move C --> B
move A --> C
move B --> A
move B --> C
move A --> C
>>>

这个方法是我在,网上找到的。还不是很清楚,希望大神能解惑。