Number of Spaces Cleaning Robot Cleaned

Simulate a robot that turns right on obstacles, halting once it revisits a state already visited in the same direction.

Medium
Time O(m*n) Space O(m*n)
5 min read
matrix simulation hashing

Problem#

An curriculum-track problem. A cleaning robot starts at the top-left of an m x n grid facing right. Each step: if the cell ahead is free, move forward and clean it; if blocked (wall or obstacle), rotate 90 degrees clockwise. The robot stops if it revisits the same cell with the same orientation. Return the number of distinct cells cleaned.

Examples#

  • room = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]]7
  • room = [[0]]1
  • room = [[0,1],[0,0]]3

Constraints#

  • 1 <= m, n <= 100, room[i][j] is 0 (empty) or 1 (obstacle), room[0][0] == 0.

Approach#

Track the robot’s (row, col, dir) state. Cells visited are stored in a separate set so we count each unique cell only once. Halt when the current (r, c, dir) is in a visited-states set — that’s a cycle and no new cleaning can happen.

Solution#

Number of Spaces Cleaning Robot Cleaned
class Solution {
public:
int numberOfCleanRooms(vector<vector<int>>& room) {
int m = room.size(), n = room[0].size();
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
set<tuple<int,int,int>> seenState;
set<pair<int,int>> cleaned;
int r = 0, c = 0, d = 0;
while (!seenState.count({r, c, d})) {
seenState.insert({r, c, d});
cleaned.insert({r, c});
int nr = r + dx[d], nc = c + dy[d];
if (nr < 0 || nr >= m || nc < 0 || nc >= n || room[nr][nc] == 1) {
d = (d + 1) % 4;
} else {
r = nr; c = nc;
}
}
return (int)cleaned.size();
}
};

Editorial#

The state space (row, col, direction) is bounded by 4 * m * n, so the simulation halts in O(m*n) steps. The cleaned set is separate because we don’t care about direction when counting unique cells.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.