2343. Count Unguarded Cells in the Grid
My accepted Python solution to LeetCode problem 2343, Count Unguarded Cells in the Grid, running in 303ms.
- Difficulty: Medium
- Python
- Runtime 303ms
- Memory 40.8MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 303ms, memory 40.8MB, accepted 2025-12-29.
class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
# Mark cells: 0=unguarded, 1=guard, 2=wall, 3=guarded
# Time: O(m*n), Space: O(m*n)
grid = [[0] * n for _ in range(m)]
# Mark guards
for r, c in guards:
grid[r][c] = 1
# Mark walls
for r, c in walls:
grid[r][c] = 2
# Directions: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# For each guard, mark cells in all 4 directions
for r, c in guards:
for dr, dc in directions:
nr, nc = r + dr, c + dc
while 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] == 1 or grid[nr][nc] == 2: # guard or wall
break
grid[nr][nc] = 3 # guarded
nr += dr
nc += dc
# Count unguarded cells
count = 0
for r in range(m):
for c in range(n):
if grid[r][c] == 0:
count += 1
return count