The Count Unguarded Cells in the Grid interview question presents a 2D matrix where some cells are occupied by "Guards" and others by "Walls." Guards can see in four directions (up, down, left, right) until their line of sight is blocked by a wall or another guard.
You need to find the total number of empty cells that are not seen (guarded) by any guard.
Companies like Microsoft and Google use this to test simulation interview pattern and matrix proficiency. It evaluates how you handle directional traversal and avoid redundant work. A naive approach might re-check cells multiple times, leading to complexity. An optimized approach ensures each cell is processed efficiently, showing an understanding of space-time tradeoffs.
The problem is solved using Grid Simulation with State Marking.
Grid , Guard at (1, 1), Wall at (1, 2).
[0, 0, 0][0, G, W][0, 0, 0]When simulating "lines of sight," always use a single character or integer to represent the cell state in a 2D array. This allows for updates and prevents you from adding the same cell to a "seen" list multiple times.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Spiral Matrix III | Medium | Solve | |
| Spiral Matrix II | Medium | Solve | |
| Diagonal Traverse | Medium | Solve | |
| Where Will the Ball Fall | Medium | Solve | |
| Game of Life | Medium | Solve |