2257 - Count Unguarded Cells in the Grid
C++
class Solution { public: int countUnguarded(int m, int n, vector<vector<int>>& guards, vector<vector<int>>& walls) { int g[m][n]; memset(g, 0, sizeof(g)); for (auto& e : guards) { g[e[0]][e[1]] = 2; } for (auto& e : walls) { g[e[0]][e[1]] = 2; } int dirs[5] = {-1, 0, 1, 0, -1}; for (auto& e : guards) { for (int k = 0; k < 4; ++k) { int x = e[0], y = e[1]; int a = dirs[k], b = dirs[k + 1]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && g[x + a][y + b] < 2) { x += a; y += b; g[x][y] = 1; } } } int ans = 0; for (auto& row : g) { ans += count(row, row + n, 0); } return ans; } };
JAVA
class Solution { public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { int[][] g = new int[m][n]; for (var e : guards) { g[e[0]][e[1]] = 2; } for (var e : walls) { g[e[0]][e[1]] = 2; } int[] dirs = {-1, 0, 1, 0, -1}; for (var e : guards) { for (int k = 0; k < 4; ++k) { int x = e[0], y = e[1]; int a = dirs[k], b = dirs[k + 1]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && g[x + a][y + b] < 2) { x += a; y += b; g[x][y] = 1; } } } int ans = 0; for (var row : g) { for (int v : row) { if (v == 0) { ++ans; } } } return ans; } }
PYTHON
class Solution: def countUnguarded(self, m, n, guards, walls): grid = [[0] * n for _ in range(m)] for x, y in guards: grid[x][y] = 2 for x, y in walls: grid[x][y] = 2 dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] for x, y in guards: for a, b in dirs: nx, ny = x, y while 0 <= nx + a < m and 0 <= ny + b < n and grid[nx + a][ny + b] < 2: nx += a ny += b grid[nx][ny] = 1 return sum(row.count(0) for row in grid)
Comments
Post a Comment