《程序员的算法趣题》-(日)增井敏克 , 书中为69 道数学谜题编写了解题程序, 编程语言为:Ruby(为主),JavaScript,C语言。有兴趣的同学,可以购书阅读~
在此更新个人编写的Python版,仅供学习使用。(运行环境:Python3.6)
Q26 高效的立体停车场
立体停车场可以充分利用窄小的土地,通过上下左右移动来停车、出库,从而尽可能多地停车。
现在有一个立体停车场,车出库时是把车往没有车的位置移动,从而把某台车移动到出库位置。假设要把左上角的车移动到右下角,试找出路径最短时的操作步数。举个例子,在 3×2 的停车场用如图所示的方式移动时,只需要移动 9 步。
问题
求在 10×10 的停车场中,把车从左上角移动到右下角时按最短路径移动时需要的最少步数。
MAX_SIZE_X = 10
MAX_SIZE_Y = 10
MIN_STEPS = None
def move_car(car_pos, null_pos, walked_steps):
global MIN_STEPS
next_x = car_pos[0]+1
if next_x <= MAX_SIZE_X:
right_steps = abs(null_pos[0]-next_x) + abs(null_pos[1]-car_pos[1]) + 1 + walked_steps
if next_x == MAX_SIZE_X and car_pos[1] == MAX_SIZE_Y:
if (not MIN_STEPS) or (right_steps < MIN_STEPS):
MIN_STEPS = right_steps
else:
move_car([next_x, car_pos[1]], car_pos, right_steps)
next_y = car_pos[1] + 1
if next_y <= MAX_SIZE_Y:
down_steps = abs(null_pos[0] - car_pos[0]) + abs(null_pos[1] - next_y) + 1 + walked_steps
if car_pos[0] == MAX_SIZE_X and next_y == MAX_SIZE_Y:
if (not MIN_STEPS) or (down_steps < MIN_STEPS):
MIN_STEPS = down_steps
else:
move_car([car_pos[0], next_y], car_pos, down_steps)
move_car([1, 1], [MAX_SIZE_X, MAX_SIZE_Y], 0)
print("最少步数为:%s" % MIN_STEPS)
运行结果:
最少步数为:69