Problem Description
A robot moves on an infinite 2D grid following a series of commands. Commands can instruct the robot to turn 90 degrees left/right or to move forward a given number of steps. The grid also contains obstacles. If the robot encounters an obstacle during a move, it stops before the obstacle and continues with the next command. The goal is to compute the maximum squared Euclidean distance from the origin reached by the robot during its journey.
Key Insights
- Use directional vectors (north, east, south, west) with an index for easy rotation.
- Store obstacles in a set for O(1) lookup when checking if the next position is blocked.
- Process each command; for move commands, simulate step-by-step movement checking for obstacles.
- Update the answer as the maximum of x² + y² after each valid step.
Space and Time Complexity
Time Complexity: O(S) where S is the total number of steps taken (each command may involve up to 9 steps).
Space Complexity: O(O) where O is the number of obstacles stored in the hash set.
Solution
The solution uses a simulation approach:
- Initialize the starting point (0, 0) facing north.
- Represent directions using two arrays dx and dy. For example, with index 0 as north, dx = [0, 1, 0, -1] and dy = [1, 0, -1, 0].
- Convert the obstacles list into a set for quick lookup.
- Loop through each command: adjust the current direction for turning commands (-1 and -2) using modulus arithmetic.
- For forward movement commands, move one unit at a time. Before each step, check if the new position is an obstacle.
- Keep track of the maximum squared distance reached.
- Return the maximum squared distance after processing all commands.
Code Solutions
Below are code solutions in multiple languages with detailed comments.