Magicsheet logo

Count Unguarded Cells in the Grid

Medium
100%
Updated 6/1/2025

Count Unguarded Cells in the Grid

What is this problem about?

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.

Why is this asked in interviews?

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 O(Gimes(M+N))O(G imes (M+N)) complexity. An optimized approach ensures each cell is processed efficiently, showing an understanding of space-time tradeoffs.

Algorithmic pattern used

The problem is solved using Grid Simulation with State Marking.

  1. Initialize a grid with states: 0 (Empty), 1 (Guard), 2 (Wall), 3 (Guarded).
  2. Mark all guards and walls on the grid first.
  3. For each guard at (r,c)(r, c):
    • Move in each of the 4 directions.
    • For each step, if the cell is a wall or another guard, stop.
    • If the cell is empty or already marked "guarded," mark it as "guarded" and continue.
  4. After all guards are processed, count the number of cells that are still "Empty."

Example explanation

Grid 3imes33 imes 3, Guard at (1, 1), Wall at (1, 2).

  1. Grid:
    • [0, 0, 0]
    • [0, G, W]
    • [0, 0, 0]
  2. Guard at (1, 1) looks:
    • Up: (0, 1) marked Guarded.
    • Down: (2, 1) marked Guarded.
    • Left: (1, 0) marked Guarded.
    • Right: Hits wall at (1, 2). Stop.
  3. Unguarded cells are the four corners: (0,0), (0,2), (2,0), (2,2). Result = 4.

Common mistakes candidates make

  • Redundant Traversal: Not stopping when hitting a wall or another guard.
  • Incorrect Order: Marking "guarded" cells before all walls are placed, which might let a guard "see through" a wall that is added later in the input list.
  • Complexity: Not using a 2D array to mark seen cells, leading to repeated O(G)O(G) searches for every cell.

Interview preparation tip

When simulating "lines of sight," always use a single character or integer to represent the cell state in a 2D array. This allows for O(1)O(1) updates and prevents you from adding the same cell to a "seen" list multiple times.

Similar Questions