[LeetCode] Count Unguarded Cells in the Grid

2257. Count Unguarded Cells in the Grid

You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.

A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.

Return the number of unoccupied cells that are not guarded.

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
26
27
28
29
30
31
32
33
class Solution {
public:
int countUnguarded(int n, int m, vector<vector<int>>& guards, vector<vector<int>>& walls) {
vector<vector<int>> g(n, vector<int>(m, 0));
int dy[4] {-1,0,1,0}, dx[4]{0,1,0,-1};
for(auto& p : guards) {
g[p[0]][p[1]] = -1;
}
for(auto& p : walls) {
g[p[0]][p[1]] = -2;
}
for(auto& p : guards) {
int y = p[0], x = p[1];
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
while(0 <= ny and ny < n and 0 <= nx and nx < m) {
if(g[ny][nx] < 0) break;
if(g[ny][nx] & (1<<((i + 2) % 4))) break;
g[ny][nx] |= (1<<i);
ny += dy[i], nx += dx[i];
}
}
}

int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(g[i][j] == 0) res++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/count-unguarded-cells-in-the-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.