Created
June 3, 2017 09:48
-
-
Save shellj/9966e413296ad1dadcbb948b412f6bc1 to your computer and use it in GitHub Desktop.
汉诺塔
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://zh.wikipedia.org/wiki/%E6%B1%89%E8%AF%BA%E5%A1%94 | |
# 分为3步进行 | |
# 1. 将a上面的n-1个移到b上(c作为中转) | |
# 2. 将a上面的那一个移到c上 | |
# 3. 将b上的那n-1个移到c上(a作为中转) | |
# 所以这个函数的四个参数为,n:层数 a:需要移动的一堆盘子 b:中转站 c:目标塔。 | |
# 注意形参和实参 | |
def hanoi(n, a='A', b='B', c='C'): | |
if n == 1: | |
print('move', a, '-->', c) | |
return | |
hanoi(n-1, a, c, b) | |
print('move', a, '-->', c) | |
hanoi(n-1, b, a, c) | |
print(hanoi(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment