Count Unguarded Cells in the Grid - Problem
Imagine you're designing a security system for a building represented by an m ร n grid. The building has guards stationed at specific positions and walls that block visibility.
Each guard can see in all four cardinal directions (north, east, south, west) from their position, but their line of sight is blocked by walls or other guards. A cell is considered "guarded" if at least one guard can see it.
Your task is to determine how many cells in the building are unoccupied and unguarded - these represent potential security vulnerabilities!
Input:
m, n: dimensions of the gridguards[][]: array of guard positions[row, col]walls[][]: array of wall positions[row, col]
Output: Number of cells that are neither occupied (by guards/walls) nor guarded.
Input & Output
example_1.py โ Basic Case
$
Input:
m = 4, n = 6
guards = [[0,0],[1,1],[2,3]]
walls = [[0,1],[2,2],[1,4]]
โบ
Output:
7
๐ก Note:
Guards can see in straight lines until blocked by walls. The unguarded cells are those that no guard can see due to walls blocking their vision or being outside all sight lines.
example_2.py โ Small Grid
$
Input:
m = 3, n = 3
guards = [[1,1]]
walls = [[0,1],[1,0],[2,1],[1,2]]
โบ
Output:
4
๐ก Note:
The guard in the center is surrounded by walls, so it can't see any other cells. All corner cells remain unguarded.
example_3.py โ No Walls
$
Input:
m = 2, n = 4
guards = [[0,0],[1,2]]
walls = []
โบ
Output:
2
๐ก Note:
With no walls, guards have clear sight lines. The first guard sees the entire first row and first column, the second guard sees remaining cells in its row and column.
Constraints
- 1 โค m, n โค 105
- 2 โค m * n โค 105
- 1 โค guards.length, walls.length โค 5 * 104
- guards[i].length == walls[j].length == 2
- 0 โค rowi, coli < m, n
- All positions in guards and walls are unique
Visualization
Tap to expand
Understanding the Visualization
1
Setup Security Grid
Place guards (green) and walls (gray) in the warehouse
2
Cast Vision Lines
Each guard looks in 4 directions: north, south, east, west
3
Mark Guarded Areas
Vision extends until hitting walls or other guards (yellow areas)
4
Identify Blind Spots
Count white cells - these are security vulnerabilities!
Key Takeaway
๐ฏ Key Insight: Instead of checking each cell individually, we simulate guard vision by tracing sight lines from each guard position. This transforms an O(m*n*g*(m+n)) brute force into an optimal O(m*n) solution by processing each cell at most 4 times.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code