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 position
  • void step(int num): Move the robot forward num steps
  • int[] 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
Walking Robot Simulation II2×3 GridR(0,0)(1,0)(1,1)(1,2)(0,2)(0,1)Operations:• Robot(2,3) - Initialize• step(2) - Move 2 steps• getPos() - Return position• getDir() - Return directionResult: [1,0], "South"
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
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
12.0K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen