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 GridInput: 4×6 GridGWGWProcess: Guards Cast VisionW?GW?Output: Count Unguarded7Blue cells = UnguardedG = GuardW = WallYellow = GuardedBlue = UnguardedGuards see in 4 directions until blocked by walls or other guardsResult: 7 cells remain unguarded and unoccupied
Understanding the Visualization
1
Input Grid
Grid with guards (G) and walls (W) placed
2
Guard Vision
Guards see in 4 directions until blocked
3
Count Result
Count cells that no guard can see
Key Takeaway
🎯 Key Insight: Guards cast vision rays in cardinal directions, stopped only by walls or other guards
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