汉诺塔python详解
代码:
'''
n:要移动盘数
src:源头柱
aid:辅助柱
dest: 目标柱
每次调用的时候注意切换辅助柱子,通过辅助柱将n-1个圆盘移动到目标柱
'''
def hnt(n,src,aid,dest):
if(n == 1):
print(str(n) +' from ' + src + ' to ' + dest)
return
hnt(n-1,src,dest,aid)
print(str(n) +' from ' + src + ' to ' + dest)
hnt(n-1,aid,src,dest)
if __name__ == '__main__':
hnt(4,'A','B','C')
输出:
1 from A to B
2 from A to C
1 from B to C
3 from A to B
1 from C to A
2 from C to B
1 from A to B
4 from A to C
1 from B to C
2 from B to A
1 from C to A
3 from B to C
1 from A to B
2 from A to C
1 from B to C