Skip to content

Commit 26bd8fd

Browse files
authored
Create 2257. Count Unguarded Cells in the Grid
1 parent 81d8863 commit 26bd8fd

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
char grid[100000];
2+
class Solution {
3+
public:
4+
int m, n, comp;
5+
int d[5] = {0, 1, 0, -1, 0};
6+
inline int idx(int r, int c) { return r * n + c; }
7+
inline void cross(int r, int c) {
8+
for (int a = 0; a < 4; a++) {
9+
int di = d[a], dj = d[a + 1];
10+
for (int i = r + di, j = c + dj;; i += di, j += dj) {
11+
int pos = idx(i, j);
12+
if (i < 0 || i >= m || j < 0 || j >= n || grid[pos] == 'X')
13+
break;
14+
comp -= (grid[pos] == ' ');
15+
grid[pos] = 'V';
16+
}
17+
}
18+
}
19+
20+
int countUnguarded(int m, int n, vector<vector<int>>& guards,
21+
vector<vector<int>>& walls) {
22+
this->m = m, this->n = n;
23+
comp = m * n;
24+
memset(grid, ' ', m * n);
25+
26+
for (auto& ij : walls) {
27+
grid[idx(ij[0], ij[1])] = 'X';
28+
comp--;
29+
}
30+
31+
for (auto& ij : guards) {
32+
grid[idx(ij[0], ij[1])] = 'X';
33+
comp--;
34+
}
35+
36+
for (auto& ij : guards) {
37+
cross(ij[0], ij[1]);
38+
}
39+
return comp;
40+
}
41+
};

0 commit comments

Comments
 (0)