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.
classSolution { public: intcountUnguarded(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 and0 <= 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; } };