游戏规则:
有A,B,C三根针,将A针上N个从小到大叠放的盘子移动到C针,一次只能移动一个,不重复移动,小盘子必须在大盘子上面。
关键分析:
将N-1个盘子从A移动到B,然后将第N个盘子从A移动到C。
剩下N-1个盘子需要从B移动到C,此时的中转站则从B变成了A(鉴于这时盘子都在B针),目标仍然是C针。
下一次重复的时候,只剩下A上的N-2个盘子需要移动(N-1与N都已经移动到了C),中转站又变成B,目标不变仍然是C针。
……整个过程中,变化的只是中转站(在A与B之间轮换),以及剩下那些所需要移动的盘子的总数(越来越少)而已。
伪代码:
FUNCTION MoveTower(disk, source, dest, spare):
IF disk == 0, THEN:
move disk from source to dest
ELSE:
MoveTower(disk - 1, source, spare, dest) // Step 1 above
move disk from source to dest // Step 2 above
MoveTower(disk - 1, spare, dest, source) // Step 3 above
END IF
代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
count = 0
def move(n, source, destination):
global count
print("move disk {0} from {1} to {2} ".format(n, source, destination))
count = count + 1
def hanoi_tower(n, source, spare, destination):
if n >= 1:
hanoi_tower(n-1, source, destination, spare)
move(n, source, destination)
hanoi_tower(n-1, spare, source, destination)
hanoi_tower(3,'A','B','C')
print("the move count is :",count)
运行结果:
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
the move count is : 7
参考:
http://www.zhihu.com/question/24385418/answer/46241635
http://www.zhihu.com/question/24385418
http://stackoverflow.com/questions/17506947/local-variable-count-referenced-before-assignment