Count Unguarded Cells in the Grid — LeetCode 2257 Python Solution

MediumArrayMatrixSimulation
Problem
#2257
Reading time
3 min

The problem

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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2257. Count Unguarded Cells in the Grid is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2257. Count Unguarded Cells in the Grid?
LeetCode 2257. Count Unguarded Cells in the Grid is rated Medium on LeetCode.
What is the time complexity of LeetCode 2257. Count Unguarded Cells in the Grid?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 2257. Count Unguarded Cells in the Grid?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 2257. Count Unguarded Cells in the Grid cover?
LeetCode 2257. Count Unguarded Cells in the Grid is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview