Sponsored
Sponsored
Simulate the movement of the robot by maintaining a variable for the current direction. Use an array to store the possible directions: north, east, south, and west. When a turn command is received, adjust the direction index. For movement commands, move the robot in the direction indexed by the current direction.
Time Complexity: O(N + M), where N is the number of commands and M is the number of obstacles.
Space Complexity: O(M), where M is the number of obstacles.
1def robotSim(commands, obstacles):
2 obstacle_set = set(map(tuple, obstacles))
3 # Directions: north, east, south, west
4 dx = [0, 1, 0, -1]
5 dy = [1, 0, -1, 0]
6 x = y = 0
7 direction = 0
8 max_distance_sq = 0
9
10 for command in commands:
11 if command == -2: # Turn left
12 direction = (direction - 1) % 4
13 elif command == -1: # Turn right
14 direction = (direction + 1) % 4
15 else:
16 for _ in range(command):
17 if (x + dx[direction], y + dy[direction]) not in obstacle_set:
18 x += dx[direction]
19 y += dy[direction]
20 else:
21 break
22 max_distance_sq = max(max_distance_sq, x * x + y * y)
23
24 return max_distance_sq
The solution defines the possible directions the robot can face using two arrays dx
and dy
. The direction is managed using a variable that cycles through the indices on executing turn commands. By maintaining a set of obstacles, it ensures efficient checks when the robot moves. The maximum squared distance is updated whenever the robot's position changes.