汉诺塔游戏

游戏规则:

有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

hanoi塔游戏规则图示及分析

http://stackoverflow.com/questions/17506947/local-variable-count-referenced-before-assignment

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值