Leetcode Problem 2257. Count Unguarded Cells in the Grid

2257. Count Unguarded Cells in the Grid

Leetcode Solutions

DFS-based Guard Visibility Check

  1. Initialize a grid of size m x n with all cells set to 0.
  2. Mark the positions of guards with 'G' and walls with 'W' in the grid.
  3. For each guard, perform DFS in the four cardinal directions (up, down, left, right).
  4. In DFS, if a cell is out of bounds, a wall, or another guard, stop the search.
  5. If a cell is empty, mark it as 'X' to indicate it is guarded, and continue the search in the same direction.
  6. After all guards have been processed, count the number of cells that are still 0 (unguarded).
  7. Return the count of unguarded cells.
UML Thumbnail

Marking Guarded Cells with Iterative Traversal

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...