[LeetCode] Number of Spaces Cleaning Robot Cleaned

2061. Number of Spaces Cleaning Robot Cleaned

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 indefinetely.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int numberOfCleanRooms(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size(), res = 1;
vector<vector<vector<int>>> vis(n, vector<vector<int>>(m, vector<int>(4, 0)));
vector<vector<int>> clean(n, vector<int>(m, 0));
clean[0][0] = true;
int y = 0, x = 0, dir = 1;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
while(!vis[y][x][dir]) {
vis[y][x][dir] = true;
if(!clean[y][x]) {
res += 1;
clean[y][x] = true;
}
int ny = y + dy[dir], nx = x + dx[dir];
if(0 > ny or ny >= n or 0 > nx or nx >= m or A[ny][nx] == 1) {
dir = (dir + 1) % 4;
} else {
y = ny, x = nx;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/01/PS/LeetCode/number-of-spaces-cleaning-robot-cleaned/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.