Count Unguarded Cells in the Grid Problem
Description
LeetCode Problem 2257.
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] = [row_i, col_i] and walls[j] = [row_j, col_j] represent the positions of the i^th guard and j^th 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.
Example 1:

Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
Example 2:

Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]
Output: 4
Explanation: The unguarded cells are shown in green in the above diagram.
There are a total of 4 unguarded cells, so we return 4.
Constraints:
1 <= m, n <= 10^52 <= m * n <= 10^51 <= guards.length, walls.length <= 5 * 10^42 <= guards.length + walls.length <= m * nguards[i].length == walls[j].length == 20 <= row_i, row_j < m0 <= col_i, col_j < n- All the positions in
guardsandwallsare unique.
Solution
Approach: Simulation
Make an m x n grid g filled with 0 (not guarded). Mark every guard and wall with 2, meaning the cell is occupied and blocks sight.
Then, from each guard, walk in the four directions until the next cell is out of bounds, a wall or another guard, marking every visited cell with 1 (guarded). Finally count the cells that are still 0.
Each cell can be visited by at most four guards' lines of sight per direction chain, so the work is bounded by the grid size times a small constant.
Complexity: O(m * n) time and O(m * n) space.
class Solution:
def countUnguarded(
self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]
) -> int:
g = [[0] * n for _ in range(m)]
for i, j in guards:
g[i][j] = 2
for i, j in walls:
g[i][j] = 2
dirs = (-1, 0, 1, 0, -1)
for i, j in guards:
for a, b in zip(dirs, dirs[1:]):
x, y = i, j
while 0 <= x + a < m and 0 <= y + b < n and g[x + a][y + b] < 2:
x, y = x + a, y + b
g[x][y] = 1
return sum(v == 0 for row in g for v in row)