Count Unguarded Cells in the Grid

You are given two integers m and n for a 0-indexed m x n grid, and two lists guards and walls, where guards[i] = [row, col] and walls[j] = [row, col] give the positions of guards and walls. A guard sees every cell in the four cardinal directions from its position until the view is blocked by a wall or another guard. A cell is guarded if at least one guard sees it. Return the number of cells that are not occupied and not guarded.

30:00

Count Unguarded Cells in the Grid
medium
Free written solution
Topics
Companies

You are given two integers m and n for a 0-indexed m x n grid, and two lists guards and walls, where guards[i] = [row, col] and walls[j] = [row, col] give the positions of guards and walls. A guard sees every cell in the four cardinal directions from its position until the view is blocked by a wall or another guard. A cell is guarded if at least one guard sees it. Return the number of cells that are not occupied and not guarded.

Example 1:
Input: {"m":4,"n":6,"guards":[[0,0],[1,1],[2,3]],"walls":[[0,1],[2,2],[1,4]]}
Output: 7
Constraints:
  • 1≤m,n≤1051 \leq m, n \leq 10^5

  • 2≤m⋅n≤1052 \leq m \cdot n \leq 10^5

  • 1≤guards.length,walls.length≤5⋅1041 \leq \text{guards.length}, \text{walls.length} \leq 5 \cdot 10^4

  • 2≤guards.length+walls.length≤m⋅n2 \leq \text{guards.length} + \text{walls.length} \leq m \cdot n

  • guards[i].length==walls[j].length==2\text{guards}[i]\text{.length} == \text{walls}[j]\text{.length} == 2

  • 0≤row<m0 \leq \text{row} < m, 0≤col<n0 \leq \text{col} < n

  • All positions in guards and walls are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"m":4,"n":6,"guards":[[0,0],[1,1],[2,3]],"walls":[[0,1],[2,2],[1,4]]}

A 4 x 6 room. Each guard sees in the four compass directions until a wall, another guard or the edge blocks the view.

room 4 x 6

guard

wall

current line of sight

guarded

unguarded

guards swept = 0

guarded = 0 / 24

unguarded = ?

Variables
VariableValue
m4
n6
guards3
walls3
DepthFunction Call
Stack empty
0/19