← DiffPush

Surrounded Regions

Standard Bar Graphs · Traversal Problems O(m * n) · O(m * n)

Quarantining the Inland Storage Yards

A security grid marks fenced yards (X) and open yards (O). Any open yard that can trace a chain of open neighbours to the outer boundary stays open — it has an escape route to the perimeter. Open pockets entirely walled in, though, get converted to fenced yards in a single lockdown sweep. Only inland pockets flip; border-touching chains never do.

Input: An m x n board of characters 'X' and 'O'.

Output: Return the board after flipping every 'O' region that is 4-directionally surrounded by 'X' to 'X'.

Constraints

Examples

Example 1

Input: {"board":[["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]}
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
The inland pocket flips, but the bottom 'O' touches the border and survives.

Example 2

Input: {"board":[["O","O"],["O","O"]]}
Output: [["O","O"],["O","O"]]
Every open yard already touches the boundary — nothing is surrounded.

Solve this in your browser →

Also on LeetCode ↗