#2257

Count Unguarded Cells in the Grid

Medium
ArrayMatrixSimulationHash Set for efficient membership checking.Grid traversal techniques (like BFS/DFS) can be useful in similar problems.
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a set to track guarded cells directly, avoiding the need for a full grid representation. This is more efficient in terms of both time and space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set to store the positions of guarded cells.
  2. 2Step 2: Add all guard and wall positions to the set to avoid counting them later.
  3. 3Step 3: For each guard, iterate in all four directions, adding cells to the set until hitting a wall or another guard.
solution.py19 lines
1def countUnguarded(m, n, guards, walls):
2    guarded = set()
3    for r, c in guards:
4        guarded.add((r, c))
5    for r, c in walls:
6        guarded.add((r, c))
7    
8    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
9    for r, c in guards:
10        for dr, dc in directions:
11            nr, nc = r, c
12            while 0 <= nr < m and 0 <= nc < n:
13                nr += dr
14                nc += dc
15                if (nr, nc) in guarded:
16                    break
17                guarded.add((nr, nc))
18    
19    return m * n - len(guarded)

Complexity note: The time complexity is O(n) because we only traverse the grid a limited number of times based on the number of guards and walls. The space complexity is O(n) due to the set storing guarded cell positions.

  • 1Guarded cells can be efficiently tracked using a set instead of a full grid.
  • 2Iterating in all four directions from each guard allows us to mark visible cells until blocked.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.