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.
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.
Examples
Example 1:
$$ \begin{array}{|c|c|c|c|c|c|} \hline G & W & \colorbox{green}{} & \colorbox{red}{} & \colorbox{green}{} & \colorbox{green}{} \\ \hline \colorbox{red}{} & G & \colorbox{red}{} & \colorbox{red}{} & W & \colorbox{green}{} \\ \hline \colorbox{red}{} & \colorbox{red}{} & W & G & \colorbox{red}{} & \colorbox{red}{} \\ \hline \colorbox{red}{} & \colorbox{red}{} & \colorbox{green}{} & \colorbox{red}{} & \colorbox{green}{} & \colorbox{green}{} \\ \hline \end{array} $$
|
|
Example 2:
$$ \begin{array}{|c|c|c|} \hline \colorbox{green}{\ \ \ \ } & W & \colorbox{green}{\ \ \ \ } \\ \hline W & G & W \\ \hline \colorbox{green}{\ \ \ \ } & W & \colorbox{green}{\ \ \ \ } \\ \hline \end{array} $$
|
|
Solution
Method 1 - DFS
To determine the count of unoccupied cells that are not guarded in an m x n
grid given the positions of guards and walls.
Here are the steps:
- Initialize the Grid:
- Create an
m x n
grid initialized with zeros. Each cell in this grid can have one of the following states:0
: Free1
: Guard2
: Wall3
: Guarded
- Create an
- Mark Guards and Walls:
- Update the grid based on the positions of guards (marking these cells as
1
). - Update the grid based on the positions of walls (marking these cells as
2
).
- Update the grid based on the positions of guards (marking these cells as
- Guard the Cells:
- For each guard, mark the cells that the guard can see in the four cardinal directions (north, south, east, and west).
- While marking, stop if you encounter another guard (
1
) or a wall (2
).
- Count the Unguarded Cells:
- Iterate through the grid and count the cells that are free (
0
).
- Iterate through the grid and count the cells that are free (
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
- Initializing the grid and marking guards and walls takes
O(m * n)
. - Marking the guarded cells for each guard might visit each cell in the grid, resulting in
O(m * n)
time. - Counting the unguarded cells takes
O(m * n)
.
- Initializing the grid and marking guards and walls takes
- 🧺 Space complexity:
O(m * n)
as we use an additional grid of sizem x n
to track the state of each cell.