在停车场中只有一个空车位。如果给出停车场的初始和最终状态,要求每次移动仅允许将车移至空车位,找到从初始至最终状态所需的最少的移动次数。
例如,初始状态数组为[1, 2, 3, 0, 4],其中1、2、3、4为不同的车,0表示空车位。最终状态为[0, 3, 2, 1, 4]。我们可以在初始数组中,交换0和1从而得到[0, 2, 3, 1, 4],每次只能和0交换。
输出结果为:
initial: [1, 2, 3, 0, 4]
final: [0, 3, 2, 1, 4]
Steps = 4
Sequence :
0 2 3 1 4
2 0 3 1 4
2 3 0 1 4
0 3 2 1 4
总起来分为三步:①顺序比较是否一致;②将不一致的移至空位;③将正确的放入空位。代码如下:
def garage(initial, final):
initial = initial[::] # prevent changes in original 'initial'
seq = [] # list of each step in sequence
steps = 0
while initial != final:
zero = initial.index(0)
if zero != final.index(0): # if zero isn't where it should be,
car_to_move = final[zero] # what should be where zero is,
pos = initial.index(car_to_move) # and where is it?
initial[zero], initial[pos] = initial[pos], initial[zero]
else:
for i in range(len(initial)):
if initial[i] != final[i]:
initial[zero], initial[i] = initial[i], initial[zero]
break
seq.append(initial[::])
steps += 1
return steps, seq