《程序员的算法趣题》-(日)增井敏克 , 书中为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种移动路径