Count Unguarded Cells in the Grid - Problem

You are given two integers m and n representing a 0-indexed m × n grid. You are also given two 2D integer arrays guards and walls where:

  • guards[i] = [row_i, col_i] represents the position of the i-th guard
  • walls[j] = [row_j, col_j] represents the position of the j-th wall

A guard can see every cell in the four cardinal directions (north, east, south, 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.

Input & Output

Example 1 — Basic Grid
$ Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
💡 Note: Guards at (0,0), (1,1), and (2,3) can see in 4 directions until blocked by walls. After marking all guarded cells, 7 cells remain unguarded.
Example 2 — Small Grid
$ Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,2],[2,1]]
Output: 4
💡 Note: Single guard at center (1,1) is surrounded by walls, can only see 4 adjacent cells. The 4 corner cells remain unguarded.
Example 3 — No Walls
$ Input: m = 2, n = 2, guards = [[0,0]], walls = []
Output: 0
💡 Note: Guard at (0,0) can see all other cells in the 2×2 grid since there are no walls blocking the view.

Constraints

  • 1 ≤ m, n ≤ 105
  • 2 ≤ m × n ≤ 105
  • 1 ≤ guards.length, walls.length ≤ 5 × 104

Visualization

Tap to expand
Count Unguarded Cells in the Grid INPUT G W G W W G Guard Wall Cell m = 4, n = 6 guards = [[0,0],[1,1],[2,3]] walls = [[0,1],[2,2],[1,4]] ALGORITHM STEPS 1 Initialize Grid Mark guards and walls 2 For Each Guard Cast rays in 4 directions 3 Mark Guarded Stop at wall or guard 4 Count Unguarded Cells not marked Ray stops at wall Guarded FINAL RESULT G W G W W G Unguarded (7) Guarded Output 7 7 unoccupied cells are not guarded Key Insight: Use a grid marking simulation: for each guard, cast rays in 4 cardinal directions until hitting a wall or another guard. Mark all cells in the ray's path as guarded. Finally, count cells that are neither occupied (guard/wall) nor guarded. Time: O(m*n*(m+n)), Space: O(m*n) TutorialsPoint - Count Unguarded Cells in the Grid | Grid Marking Simulation
Asked in
Google 8 Amazon 5 Microsoft 4
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen