Leetcode #2257: Count Unguarded Cells in the Grid
In this guide, we solve Leetcode #2257 Count Unguarded Cells in the Grid in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Matrix, Simulation
Intuition
Grid problems are easiest when you define clear row/column boundaries.
A consistent traversal order prevents off-by-one errors.
Approach
Iterate by rows, columns, or layers depending on the requirement.
Keep bounds updated as the traversal progresses.
Steps:
- Define bounds or directions.
- Visit cells in order.
- Update result and move bounds.
Example
Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
Output: 7
Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
Python Solution
class Solution:
def countUnguarded(
self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]
) -> int:
g = [[0] * n for _ in range(m)]
for i, j in guards:
g[i][j] = 2
for i, j in walls:
g[i][j] = 2
dirs = (-1, 0, 1, 0, -1)
for i, j in guards:
for a, b in pairwise(dirs):
x, y = i, j
while 0 <= x + a < m and 0 <= y + b < n and g[x + a][y + b] < 2:
x, y = x + a, y + b
g[x][y] = 1
return sum(v == 0 for row in g for v in row)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.