《程序员的算法趣题》-(日)增井敏克 , 书中为69 道数学谜题编写了解题程序, 编程语言为:Ruby(为主),JavaScript,C语言。有兴趣的同学,可以购书阅读~
在此更新个人编写的Python版,仅供学习使用。(运行环境:Python3.6)
Q27 禁止右转也没关系吗
在像日本这样车辆靠左通行的道路上,开车左转比右转要舒服些。因为不用担心对面来车,所以只要一直靠左行驶,就不用思考怎么变道。那么,现在来想一下如何只靠直行或者左转到达目的地。假设在像图一样的网状道路上,我们只能直行或者左转,并且已经通过的道路就不能再次通过了。此时允许通行道路有交叉。
请思考一下从左下角去右上角时,满足条件的行驶路线共有多少种。举个例子,如果是像图这样 3×2 的网状道路,则共有 4 种行驶路线。
问题
求 6×4 的情况下,共有多少种行驶路线?
X_POINT = 6
Y_POINT = 4
START_POINT = (0, Y_POINT)
END_POINT = (X_POINT, 0)
AVAILABLE_DIRECTION = [(1, 0), (0, -1), (-1, 0), (0, 1)]
PATH_NUMBER = 0
def drive(cur_point, direction, drove_path):
straight = tuple(map(sum, zip(cur_point, direction)))
left_direction = AVAILABLE_DIRECTION[(AVAILABLE_DIRECTION.index(direction)+1)%len(AVAILABLE_DIRECTION)]
left = tuple(map(sum, zip(cur_point, left_direction)))
next_point_list = [(straight, direction), (left, left_direction)]
for next_point, drive_direction in next_point_list:
if 0 <= next_point[0] <= X_POINT and 0 <= next_point[1] <= Y_POINT:
path = [cur_point, next_point]
path.sort()
if path not in drove_path:
if next_point[0] == END_POINT[0] and next_point[1] == END_POINT[1]:
global PATH_NUMBER
PATH_NUMBER += 1
else:
drive(next_point, drive_direction, drove_path+[path])
drive(START_POINT, (1, 0), [])
print("共有%s种行驶路线" % PATH_NUMBER)
运行结果:
共有2760种行驶路线

241




被折叠的 条评论
为什么被折叠?



