Walking Robot Simulation

Medium Topics Company Tags

A robot begins at (0, 0) facing north on a coordinate plane. Process the instructions in commands in order:

  • -2: turn left by 90 degrees.
  • -1: turn right by 90 degrees.
  • A value from 1 to 9: move forward that many unit steps.

The coordinates in obstacles cannot be entered. If a forward step would enter an obstacle, stop that movement command and proceed to the next command. An obstacle at (0, 0) does not prevent the robot from starting there, but it prevents the robot from returning after leaving.

North increases y, east increases x, south decreases y, and west decreases x. Return the greatest value of x * x + y * y reached anywhere along the path, including the starting point.

Example 1:

Input: commands = [3,-1,2]
obstacles = []

Output: 13

Explanation: The robot moves north to (0,3), turns east, then reaches (2,3). Its greatest squared distance is 2 × 2 + 3 × 3 = 13.

Example 2:

Input: commands = [4,-1,3]
obstacles = [[0,2]]

Output: 10

Explanation: The obstacle stops the first command at (0,1). After turning east, the robot reaches (3,1), whose squared distance is 3 × 3 + 1 × 1 = 10.

Example 3:

Input: commands = [3,-1,-1,3]
obstacles = [[0,0]]

Output: 9

Explanation: The robot may leave the origin even though it is blocked. It reaches (0,3), turns around, and stops at (0,1) before returning to the obstacle. The greatest squared distance reached is 9.

Constraints:

  • 1 <= commands.length <= 10000
  • Each command is -2, -1, or an integer from 1 to 9.
  • 0 <= obstacles.length <= 10000
  • Each obstacle contains exactly two coordinates, both between -30000 and 30000.
  • The answer is less than 2147483648.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.