Walking Robot Simulation

A robot on an infinite XY-plane starts at `(0, 0)` facing north. It receives a sequence of commands `moves` (LeetCode calls this parameter `commands`): - `-2`: turn left 90 degrees. - `-1`: turn right 90 degrees. - `1 <= k <= 9`: move forward `k` units, one unit at a time. Some grid squares are obstacles; the `i`-th one is at `obstacles[i] = (x_i, y_i)`. If the robot would step onto an obstacle, it stays where it is and moves on to the next command. Return *the **maximum squared Euclidean distance** from the origin that the robot ever reaches* (for example, if the distance is 5, return 25). **Note:** north is +Y, east is +X, south is -Y, west is -X. An obstacle may sit at the origin; the robot ignores it until it moves off, and cannot return there afterwards.

30:00

Walking Robot Simulation
medium
Free written solution
Topics
Companies

A robot on an infinite XY-plane starts at (0, 0) facing north. It receives a sequence of commands moves (LeetCode calls this parameter commands):

  • -2: turn left 90 degrees.
  • -1: turn right 90 degrees.
  • 1 <= k <= 9: move forward k units, one unit at a time.

Some grid squares are obstacles; the i-th one is at obstacles[i] = (x_i, y_i). If the robot would step onto an obstacle, it stays where it is and moves on to the next command.

Return the maximum squared Euclidean distance from the origin that the robot ever reaches (for example, if the distance is 5, return 25).

Note: north is +Y, east is +X, south is -Y, west is -X. An obstacle may sit at the origin; the robot ignores it until it moves off, and cannot return there afterwards.

Example 1:
Input: {"moves":[4,-1,3],"obstacles":[]}
Output: 25
Constraints:
  • 1≤moves.length≤1041 \leq \text{moves.length} \leq 10^4

  • moves[i]\text{moves}[i] is −2-2, −1-1, or in [1,9][1, 9]

  • 0≤obstacles.length≤1040 \leq \text{obstacles.length} \leq 10^4

  • −3×104≤xi,yi≤3×104-3 \times 10^4 \leq x_i, y_i \leq 3 \times 10^4

  • The answer is guaranteed to be less than 2312^{31}.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"moves":[4,-1,3],"obstacles":[]}

Put the 0 obstacles in a hash set so each step can check its target square in O(1). The robot starts at (0, 0) facing north.

commands

4
R
3

position

(0, 0)

facing

N

x² + y²

0

best

0

robot (arrow = facing)
path walked
obstacle
farthest point so far
Variables
VariableValue
x0
y0
dirnorth
best0
DepthFunction Call
Stack empty
0/12