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 robotstep(num)- Move the robot forwardnumstepsgetPos()- 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, andgetDir.
Visualization
Tap to expand
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code