Walking Robot Simulation II - Problem

Imagine a robot explorer navigating a rectangular grid world! The robot starts at the bottom-left corner (0, 0) of a width ร— height grid, initially facing East. The grid extends from (0, 0) to (width-1, height-1).

Here's how our robot behaves:

  • When instructed to move forward, it attempts to step in its current direction
  • If it hits a boundary, it smartly turns 90ยฐ counterclockwise and tries again
  • It keeps turning and trying until it successfully moves forward

Your task: Implement a Robot class that can:

  • Robot(width, height) - Initialize the grid and robot
  • step(num) - Move the robot forward num steps
  • getPos() - Return current position as [x, y]
  • getDir() - Return current direction: "North", "East", "South", or "West"

This problem tests your ability to simulate movement with boundary handling and efficient position tracking!

Input & Output

example_1.py โ€” Basic Robot Movement
$ Input: Robot(6, 3), step(2), getPos(), getDir(), step(2), getPos(), getDir(), step(2), getPos(), getDir()
โ€บ Output: [2, 0], "East", [4, 0], "East", [6, 1], "North"
๐Ÿ’ก Note: Robot moves 2 steps East to (2,0), then 2 more steps East to (4,0), then 2 more steps: 1 East to edge, turns North, 1 North to (5,1)
example_2.py โ€” Complete Perimeter Loop
$ Input: Robot(3, 3), step(8), getPos(), getDir()
โ€บ Output: [0, 0], "South"
๐Ÿ’ก Note: Perimeter = 2*(3+3-2) = 8 steps. After 8 steps robot completes one full loop and returns to origin, but now facing South instead of East
example_3.py โ€” Edge Case: 1x1 Grid
$ Input: Robot(1, 1), step(100), getPos(), getDir()
โ€บ Output: [0, 0], "East"
๐Ÿ’ก Note: In a 1x1 grid, robot cannot move anywhere and stays at (0,0) facing East regardless of step count

Constraints

  • 2 โ‰ค width, height โ‰ค 100
  • 1 โ‰ค num โ‰ค 105
  • At most 104 calls will be made to step, getPos, and getDir.

Visualization

Tap to expand
STARTPerimeter FormulaLength = 2ร—(w + h - 2)Position = steps % lengthEdge Segments:Bottom: [0, width) โ†’ EastRight: [width, width+h-1) โ†’ NorthTop: [width+h-1, 2w+h-2) โ†’ WestLeft: [2w+h-2, 2w+2h-4) โ†’ South
Understanding the Visualization
1
The Track
Robot follows a rectangular perimeter path: East โ†’ North โ†’ West โ†’ South
2
Track Length
Total perimeter = 2ร—(width + height - 2) for rectangles
3
Position Calculation
steps % perimeter gives position on the track
4
Coordinate Mapping
Map track position back to (x,y) coordinates and direction
Key Takeaway
๐ŸŽฏ Key Insight: The robot's movement forms a predictable cycle around the grid's perimeter, allowing us to use modular arithmetic for instant position calculation instead of step-by-step simulation!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~25 min Avg. Time
890 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