Skip to main content
Back to problems
#2257
Medium Algorithms

Count unguarded cells in the grid

Array Matrix Simulation
69.0% acceptance
Feb 25, 2026
1291
91
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. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn count_unguarded(m: i32, n: i32, guards: Vec<Vec<i32>>, walls: Vec<Vec<i32>>) -> i32 {
    let (m, n) = (m as usize, n as usize);
    // 0=empty, 1=guard, 2=wall, 3=guarded
    let mut grid = vec![vec![0u8; n]; m];
    for g in &guards { grid[g[0] as usize][g[1] as usize] = 1; }
    for w in &walls { grid[w[0] as usize][w[1] as usize] = 2; }

    // Row sweeps
    for r in 0..m {
      let mut guarding = false;
      for c in 0..n {
        match grid[r][c] {
          1 => guarding = true,
          2 => guarding = false,
          0 if guarding => grid[r][c] = 3,
          _ => {}
        }
      }
      guarding = false;
      for c in (0..n).rev() {
        match grid[r][c] {
          1 => guarding = true,
          2 => guarding = false,
          0 if guarding => grid[r][c] = 3,
          _ => {}
        }
      }
    }

    // Col sweeps
    for c in 0..n {
      let mut guarding = false;
      for r in 0..m {
        match grid[r][c] {
          1 => guarding = true,
          2 => guarding = false,
          0 if guarding => grid[r][c] = 3,
          _ => {}
        }
      }
      guarding = false;
      for r in (0..m).rev() {
        match grid[r][c] {
          1 => guarding = true,
          2 => guarding = false,
          0 if guarding => grid[r][c] = 3,
          _ => {}
        }
      }
    }

    grid.iter().flatten().filter(|&&v| v == 0).count() as i32
  }
}