1
+ """
2
+ There is a parking lot with only one empty spot. Given the initial state
3
+ of the parking lot and the final state. Each step we are only allowed to
4
+ move a car
5
+ out of its place and move it into the empty spot.
6
+ The goal is to find out the least movement needed to rearrange
7
+ the parking lot from the initial state to the final state.
8
+
9
+ Say the initial state is an array:
10
+
11
+ [1, 2, 3, 0, 4],
12
+ where 1, 2, 3, 4 are different cars, and 0 is the empty spot.
13
+
14
+ And the final state is
15
+
16
+ [0, 3, 2, 1, 4].
17
+ We can swap 1 with 0 in the initial array to get [0, 2, 3, 1, 4] and so on.
18
+ Each step swap with 0 only.
19
+
20
+ Edit:
21
+ Now also prints the sequence of changes in states.
22
+ Output of this example :-
23
+
24
+ initial: [1, 2, 3, 0, 4]
25
+ final: [0, 3, 2, 1, 4]
26
+ Steps = 4
27
+ Sequence :
28
+ 0 2 3 1 4
29
+ 2 0 3 1 4
30
+ 2 3 0 1 4
31
+ 0 3 2 1 4
32
+ """
33
+
34
+
35
+ def garage (initial , final ):
36
+
37
+ initial = initial [::] # prevent changes in original 'initial'
38
+ seq = [] # list of each step in sequence
39
+ steps = 0
40
+ while initial != final :
41
+ zero = initial .index (0 )
42
+ if zero != final .index (0 ): # if zero isn't where it should be,
43
+ car_to_move = final [zero ] # what should be where zero is,
44
+ pos = initial .index (car_to_move ) # and where is it?
45
+ initial [zero ], initial [pos ] = initial [pos ], initial [zero ]
46
+ else :
47
+ for i in range (len (initial )):
48
+ if initial [i ] != final [i ]:
49
+ initial [zero ], initial [i ] = initial [i ], initial [zero ]
50
+ break
51
+ seq .append (initial [::])
52
+ steps += 1
53
+
54
+ return steps , seq
55
+ # e.g.: 4, [{0, 2, 3, 1, 4}, {2, 0, 3, 1, 4},
56
+ # {2, 3, 0, 1, 4}, {0, 3, 2, 1, 4}]
57
+
58
+ """
59
+ thus:
60
+ 1 2 3 0 4 -- zero = 3, true, car_to_move = final[3] = 1,
61
+ pos = initial.index(1) = 0, switched [0], [3]
62
+ 0 2 3 1 4 -- zero = 0, f, initial[1] != final[1], switched 0,1
63
+ 2 0 3 1 4 -- zero = 1, t, car_to_move = final[1] = 3,
64
+ pos = initial.index(3) = 2, switched [1], [2]
65
+ 2 3 0 1 4 -- zero = 2, t, car_to_move = final[2] = 2,
66
+ pos = initial.index(2) = 0, switched [0], [2]
67
+ 0 3 2 1 4 -- initial == final
68
+ """
0 commit comments