Number of Spaces Cleaning Robot Cleaned - Problem
Imagine a robotic vacuum cleaner navigating through your room! 🤖
You're given a 2D binary matrix
The robot follows a simple algorithm:
• Move straight until it hits an object or room boundary
• Turn 90 degrees clockwise
• Repeat this process indefinitely
Every space the robot visits gets cleaned. Your task is to determine how many unique spaces will be cleaned if the robot runs forever.
Note: The top-left corner
You're given a 2D binary matrix
room where 0 represents an empty space and 1 represents a space with an object (like furniture). A cleaning robot starts at the top-left corner (0,0) facing right.The robot follows a simple algorithm:
• Move straight until it hits an object or room boundary
• Turn 90 degrees clockwise
• Repeat this process indefinitely
Every space the robot visits gets cleaned. Your task is to determine how many unique spaces will be cleaned if the robot runs forever.
Note: The top-left corner
(0,0) is always empty in test cases. Input & Output
example_1.py — Python
$
Input:
room = [[0,0,0],[0,1,0],[0,0,0]]
›
Output:
7
💡 Note:
Robot starts at (0,0) and moves: right to (0,1), right to (0,2), down to (1,2), down to (2,2), left to (2,1), left to (2,0), up to (1,0), then cycles. All 7 empty spaces get cleaned.
example_2.py — Python
$
Input:
room = [[0,1,0],[1,0,1],[0,1,0]]
›
Output:
1
💡 Note:
Robot starts at (0,0) but is immediately blocked by obstacles in all directions after first turn. Only the starting position (0,0) gets cleaned.
example_3.py — Python
$
Input:
room = [[0,0],[0,0]]
›
Output:
4
💡 Note:
In a 2x2 empty room, robot visits all 4 positions: starts at (0,0), goes to (0,1), then (1,1), then (1,0), and cycles back. All positions get cleaned.
Visualization
Tap to expand
Understanding the Visualization
1
Start Position
Robot begins at top-left corner (0,0) facing right
2
Forward Movement
Robot moves forward in current direction until blocked
3
Right Turn
When blocked, robot turns 90° clockwise
4
Cycle Detection
Track (position, direction) pairs to detect when robot repeats a state
Key Takeaway
🎯 Key Insight: The robot will eventually return to a previously visited (position, direction) state, creating a cycle. We only need to simulate until this cycle is detected!
Time & Space Complexity
Time Complexity
O(m×n)
In worst case, robot visits all m×n positions multiple times before entering cycle
✓ Linear Growth
Space Complexity
O(m×n)
Need to store visited positions and state history
⚡ Linearithmic Space
Constraints
- 1 ≤ room.length, room[i].length ≤ 300
- room[i][j] is either 0 or 1
- room[0][0] == 0 (starting position is always empty)
- The room is surrounded by walls (implicit boundary)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code