《程序员的算法趣题》-(日)增井敏克 Python解题 -- (Q08)

《程序员的算法趣题》-(日)增井敏克 , 书中为69 道数学谜题编写了解题程序, 编程语言为:Ruby,JavaScript,C语言。有兴趣的同学,可以购书阅读~

在此更新个人编写的Python版,仅供学习使用。(运行环境:Python3.6)

Q08 优秀的扫地机器人
    假设有一款不会反复清扫同一个地方的机器人,它只能前后左右移动。举个例子,如果第 1 次向后移动,那么连续移动 3 次时,就会有以下 9 种情况。又因为第 1 次移动可以是前后左右 4 种情况,所以移动 3 次时全部路径有 9×4 = 36 种。 
                             

问题
       求这个机器人移动 12 次时,有多少种移动路径?

walk_steps = 12

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
all_footprint = [[(0, 0)]]
for i in range(walk_steps):
    all_new_footprint = []
    while len(all_footprint) > 0:
        cur_footprint = all_footprint.pop()
        for direction in directions:
            next_step = (cur_footprint[-1][0] + direction[0], cur_footprint[-1][1] + direction[1])
            if next_step in cur_footprint:
                continue
            else:
                all_new_footprint.append(cur_footprint + [next_step])
    all_footprint = all_new_footprint[:]
    
print('有%s种移动路径' % len(all_footprint))

运行结果:

            有324932种移动路径

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值