Walking Robot Simulation - Problem
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array of integers commands, which represents a sequence of moves that it needs to execute.
There are only three possible types of instructions the robot can receive:
-2: Turn left 90 degrees-1: Turn right 90 degrees1 <= k <= 9: Move forwardkunits, one unit at a time
Some of the grid squares are obstacles. The i-th obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, it will stay in its current location (on the block adjacent to the obstacle) and move onto the next command.
Return the maximum squared Euclidean distance that the robot reaches at any point in its path (i.e. if the distance is 5, return 25).
Note:
- There can be an obstacle at
(0, 0). If this happens, the robot will ignore the obstacle until it has moved off the origin. However, it will be unable to return to(0, 0)due to the obstacle. - North means +Y direction, East means +X direction, South means -Y direction, West means -X direction.
Input & Output
Example 1 — Basic Movement with Obstacles
$
Input:
commands = [4,-1,4,-2,-1,-2,3], obstacles = [[2,1],[1,1]]
›
Output:
25
💡 Note:
Robot moves (0,0)→(0,1)→(0,2)→(0,3)→(0,4), turns right to face East, tries to move but hits obstacle at (1,1), continues with other commands. Maximum distance reached is √25 = 5, so return 25.
Example 2 — No Obstacles
$
Input:
commands = [4,-1,3], obstacles = []
›
Output:
25
💡 Note:
Robot moves North 4 units to (0,4), turns right to face East, moves 3 units to (3,4). Max distance² = 3² + 4² = 9 + 16 = 25.
Example 3 — Blocked at Origin
$
Input:
commands = [1,2,-2,5], obstacles = [[0,1]]
›
Output:
0
💡 Note:
Robot tries to move North but hits obstacle at (0,1) immediately. Stays at (0,0) and processes remaining commands but never moves. Max distance² = 0.
Constraints
- 1 ≤ commands.length ≤ 104
- commands[i] is either -2, -1, or in the range [1, 9]
- 0 ≤ obstacles.length ≤ 104
- -3 × 104 ≤ xi, yi ≤ 3 × 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Robot commands and obstacle positions
2
Process
Simulate movement with obstacle checking
3
Output
Maximum squared Euclidean distance
Key Takeaway
🎯 Key Insight: Use hash set for O(1) obstacle detection during step-by-step robot simulation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code