Problem Description
Given an m x n grid, some cells are occupied by guards and walls. A guard “sees” (or defends) every cell in the four cardinal directions (north, east, south, west) from their position until their view is blocked by a wall or another guard. The task is to count how many cells remain that are unoccupied (i.e. not a wall or guard) and unguarded (i.e. not seen by any guard).
Key Insights
- Represent the grid as a 2D array. Since m * n is bounded by 10^5, it is efficient to use a grid even if m or n individually may be large.
- Mark positions occupied by walls and guards with distinct markers.
- For each guard, simulate the four directions. Continue marking cells as guarded until a wall or another guard is encountered.
- Count the cells that remain unmarked (thus, unoccupied by walls/guards and unguarded).
Space and Time Complexity
Time Complexity: O(m * n + g * (direction length)), where g is the number of guards. In worst-case, it is O(m * n) since m * n ≤ 10^5. Space Complexity: O(m * n) for storing the grid.
Solution
We solve the problem by first initializing a grid with default values. We mark walls and guards in the grid. Then, for every guard, we simulate spreading in all four cardinal directions (up, down, left, right). In each direction, we continue marking cells as “guarded” until we hit a wall or another guard. Finally, we iterate over the grid to count cells that are not occupied (by a guard or wall) and not marked guarded. This approach leverages simple grid simulation with careful bounds checking.