Number of Spaces Cleaning Robot Cleaned - Problem
A room is represented by a 0-indexed 2D binary matrix room where a 0 represents an empty space and a 1 represents a space with an object.
The top left corner of the room will be empty in all test cases. A cleaning robot starts at the top left corner of the room and is facing right.
The robot will continue heading straight until it reaches the edge of the room or it hits an object, after which it will turn 90 degrees clockwise and repeat this process.
The starting space and all spaces that the robot visits are cleaned by it. Return the number of clean spaces in the room if the robot runs indefinitely.
Input & Output
Example 1 — Simple 3x3 Room
$
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), (0,2), then hits boundary and turns down to (1,2), then hits obstacle at (1,1) and continues cleaning path until cycle. Cleans 7 unique positions.
Example 2 — Single Row
$
Input:
room = [[0,1,0,0]]
›
Output:
1
💡 Note:
Robot starts at (0,0), tries to move right but hits obstacle at (0,1), turns down but hits boundary, continues turning until back to original state. Only position (0,0) is cleaned.
Example 3 — Open Rectangle
$
Input:
room = [[0,0],[0,0]]
›
Output:
4
💡 Note:
Robot can move in a rectangular pattern: (0,0) → (0,1) → (1,1) → (1,0) → back to (0,0), cleaning all 4 positions.
Constraints
- 1 ≤ room.length, room[i].length ≤ 300
- room[i][j] is either 0 or 1
- room[0][0] == 0
Visualization
Tap to expand
Understanding the Visualization
1
Input Room
2D grid with obstacles (1) and empty spaces (0)
2
Robot Movement
Robot moves straight until hitting obstacle, then turns clockwise
3
Count Cleaned
Return number of unique positions visited before cycle
Key Takeaway
🎯 Key Insight: The robot will eventually enter a cycle when it returns to a previously visited state (position + direction)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code