Walking Robot Simulation II - Problem
A robot is placed on a rectangular grid of width × height cells, with the bottom-left corner at position (0, 0) and the top-right corner at (width - 1, height - 1). The robot initially starts at (0, 0) facing East.
The robot can be instructed to move a specific number of steps. For each step:
- It attempts to move forward one cell in its current direction
- If the next cell is out of bounds, the robot turns 90 degrees counterclockwise and retries the step
Implement the Robot class with the following methods:
Robot(int width, int height): Initialize the grid and robot positionvoid step(int num): Move the robot forward num stepsint[] getPos(): Return current position as [x, y]String getDir(): Return current direction ("North", "East", "South", "West")
Input & Output
Example 1 — Basic Robot Operations
$
Input:
Robot(2, 3), step(2), getPos(), getDir(), step(2), getPos(), getDir(), step(2), getPos(), getDir()
›
Output:
[null, null, [1,0], "South", null, [1,1], "West", null, [0,1], "North"]
💡 Note:
Initialize 2×3 grid. Step 2: (0,0)→(1,0)→hit boundary→turn South→(1,1). Continue stepping around the perimeter.
Example 2 — Single Cell Grid
$
Input:
Robot(1, 1), step(2), getPos(), getDir()
›
Output:
[null, null, [0,0], "East"]
💡 Note:
In a 1×1 grid, robot cannot move and stays at (0,0) facing East regardless of steps.
Example 3 — Large Step Count
$
Input:
Robot(2, 2), step(100), getPos(), getDir()
›
Output:
[null, null, [0,0], "East"]
💡 Note:
2×2 grid has perimeter cycle of length 4. After 100 steps (100%4=0), robot returns to start position.
Constraints
- 2 ≤ width, height ≤ 100
- 1 ≤ num ≤ 105
- At most 104 calls to step, getPos, and getDir
Visualization
Tap to expand
Understanding the Visualization
1
Input
Robot on 2×3 grid starting at (0,0) facing East
2
Movement
Robot steps forward, turning counterclockwise when hitting boundaries
3
Output
Track position and direction after each operation
Key Takeaway
🎯 Key Insight: The robot follows a predictable perimeter cycle, enabling efficient position calculation using modular arithmetic
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code