⚡Flashcard Drill➔
NeetCode #156LC-2257MediumArrays & Hashing
← Back to All Problems

#156 · #2257 · Count Unguarded Cells in the Grid(统计网格图中没有被保卫的格子数)

📌 Problem Statement & Constraints

You are given two integers m and n and a 2D grid where 0 is an empty cell, 1 is a guard and 2 is a wall. A guard sees every cell in the four cardinal directions until blocked by a wall or another guard. Return the number of unguarded cells. Constraints: 1 <= m, n <= 10^5, 2 <= m * n <= 10^5.

💡 Core Algorithmic Approaches

  1. Use a separate status grid so the original grid stays intact: 0 unguarded, 1 guarded, 2 guard, 3 wall.
  2. Copy the guards and walls into the status grid.
  3. For each guard, walk in all four directions, marking every empty cell as guarded and stopping at a wall.
  4. Count the remaining zeros.
  5. Note that guards themselves also block other guards' vision, which the walk handles naturally because a guard cell is not marked as guarded but does stop the loop? -- it does not stop the loop, so the guard's own cell is simply skipped when counting (it is 2, not 0).

💻 Benchmark Python3 Implementation

class Solution:
    def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
        # 0 = unguarded, 1 = guarded, 2 = guard, 3 = wall
        cell = [[0] * n for _ in range(m)]
        for r, c in guards:
            cell[r][c] = 2
        for r, c in walls:
            cell[r][c] = 3
        dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
        for r, c in guards:
            for dr, dc in dirs:
                x, y = r + dr, c + dc
                while 0 <= x < m and 0 <= y < n and cell[x][y] != 3:
                    if cell[x][y] == 0:
                        cell[x][y] = 1     # mark as guarded
                    x += dr
                    y += dc
        return sum(1 for r in range(m) for c in range(n) if cell[r][c] == 0)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m * n) in the worst case: each guard walks until a wall, and each cell is visited a constant number of times per direction.
💾 Space Complexity
O(m * n) for the status grid. Mutating the input grid instead would save this but destroys the guard positions needed for the second pass.

⚠️ Interview Pitfalls & Follow-ups

  • Mutating the input grid: the guard positions are needed for the second pass, so a separate status grid is required (or the guards must be collected first).
  • Stopping the walk at another guard: the loop condition is cell[x][y] != 3, so only walls block the sweep. Guard cells carry status 2, which means they are never overwritten as guarded and are never counted as unguarded either -- both behaviours are correct.
  • Counting guards or walls as unguarded: only status 0 counts.
  • Using a 2D list of size m x n when m * n <= 10^5 but one dimension can be 10^5: the product is bounded, so the allocation is safe.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

统计网格图中没有被保卫的格子数

给你两个整数 m 和 n 表示一个下标从 0 开始的 m × n 网格图。同时给你两个二维整数数组 guards 和 walls,其中 guards[i] = [rowi, coli] 表示第 i 个守卫的位置, walls[j] = [rowj, colj] 表示第 j 堵墙的位置。守卫能看到同一行或同一列上所有未被墙阻挡的格子(守卫本身和墙不计入)。请你返回没有被任何守卫看到的格子数目。约束:1 ≤ m, n ≤ 10^5;2 ≤ m × n ≤ 10^5;0 ≤ guards.length, walls.length ≤ 5 × 10^4;守卫和墙不会重叠。

核心要点

  • 网格标记 + 四方向扩散(标准解) :用二维数组记录每个格子的状态:0 = 空、1 = 守卫、2 = 墙、3 = 已被看到。
  • 先布置守卫与墙 :遍历两个数组完成标记。
  • 从每个守卫向四个方向扩散 :沿每个方向前进,遇到守卫或墙则停止,沿途把空格标记为「已看到」。
  • 统计 0 的个数 :遍历整个网格,状态仍为 0 的即为未被看到的格子。
  • 复杂度分析 :每个格子最多被 4 个方向各访问一次(一旦标记为 3 仍会被继续扫描但代价恒定),总代价 O(m · n + guards × max(m, n)),在 m × n ≤ 10^5 的约束下可接受。

常见陷阱

  • 扩散时把已标记为 SEEN 的格子当作阻挡 :会提前停止扩散,导致漏标记。只有 守卫 和 墙 才阻挡视线。
  • 忘记检查边界 : while 条件必须同时判断四个边界,漏掉任一个会越界(Python 中负下标会静默索引到末尾)。
  • 统计时把 SEEN 也算进去 :只统计状态为 FREE 的格子。
  • 守卫与墙的位置被覆盖 :题目保证两者不重叠,但若先布置墙再布置守卫,守卫会覆盖墙的标记——必须保证两者都被正确设置(本解先守卫后墙,由于不重叠故无冲突)。

参考实现

class Solution:
    def countUnguarded(self, m: int, n: int, guards: list[list[int]],
                       walls: list[list[int]]) -> int:
        FREE, GUARD, WALL, SEEN = 0, 1, 2, 3
        grid = [[FREE] * n for _ in range(m)]
        for r, c in guards:
            grid[r][c] = GUARD
        for r, c in walls:
            grid[r][c] = WALL

        for r, c in guards:
            for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):
                nr, nc = r + dr, c + dc
                while 0 <= nr < m and 0 <= nc < n:
                    if grid[nr][nc] == GUARD or grid[nr][nc] == WALL:
                        break               # 被守卫或墙阻挡
                    grid[nr][nc] = SEEN
                    nr += dr
                    nc += dc

        return sum(1 for r in range(m) for c in range(n) if grid[r][c] == FREE)