@@ -12,43 +12,49 @@ def robotSim(self, commands, obstacles):
1212 :type obstacles: List[List[int]]
1313 :rtype: int
1414 """
15- direction = {0 : (0 , 1 ),
16- 90 : (1 , 0 ),
17- 180 : (0 , - 1 ),
18- 270 : (- 1 , 0 ),
19- - 90 : (- 1 , 0 ),
20- - 180 : (0 , - 1 ),
21- - 270 : (1 , 0 )}
22- angle = 0
23- path = (0 , 0 )
24- res = float ('-inf' )
25- obstacle_set = set (map (tuple , obstacles ))
26- for cmd in commands :
27- # reset angle
28- if abs (angle ) == 360 :
29- angle = 0
30- if cmd in [- 1 , - 2 ]:
31- angle = (angle + 90 ) if cmd == - 1 else (angle - 90 )
32- else :
33- x , y = path
34- x_i , y_i = direction [angle ]
35-
36- for _ in range (cmd ):
37- x += x_i
38- y += y_i
39- if (x , y ) in obstacle_set :
40- break
41- path = (x , y )
42-
43- res = max (res , path [0 ]** 2 + path [1 ]** 2 )
44- return res
15+ obstacles_set = set ((x , y ) for x , y in obstacles )
16+ directions = [
17+ (0 , 1 ),
18+ (1 , 0 ),
19+ (0 , - 1 ),
20+ (- 1 , 0 ),
21+ ]
22+ direction_index = 0
23+ x = 0
24+ y = 0
25+ max_distance = 0
26+
27+ for command in commands :
28+ if command == - 1 :
29+ direction_index = (direction_index + 1 ) % 4
30+ continue
31+
32+ if command == - 2 :
33+ direction_index = (direction_index - 1 ) % 4
34+ continue
35+
36+ dx , dy = directions [direction_index ]
37+ while command > 0 :
38+ next_x = x + dx
39+ next_y = y + dy
40+ if (next_x , next_y ) in obstacles_set :
41+ break
42+
43+ x = next_x
44+ y = next_y
45+ max_distance = max (max_distance , x * x + y * y )
46+ command -= 1
47+
48+ return max_distance
4549
4650
4751class TestSolution (unittest .TestCase ):
4852
4953 def test_robotSim (self ):
5054 solution = Solution ()
55+ self .assertEqual (solution .robotSim ([4 , - 1 , 3 ], []), 25 )
5156 self .assertEqual (solution .robotSim ([4 , - 1 , 4 , - 2 , 4 ], [[2 , 4 ]]), 65 )
57+ self .assertEqual (solution .robotSim ([- 1 , - 2 , - 1 , - 2 ], []), 0 )
5258
5359
5460if __name__ == '__main__' :
0 commit comments