Surrounded Regions

Given a board of X and O, capture all regions surrounded by X by flipping every O that is not connected to the border. Pattern focus: Flood fill. Mark border-connected O cells first, then flip the rest.

Input Format

board = 2D character grid

Output Format

board after capturing surrounded regions

Constraints

  • 1 <= rows * cols <= 10^5
  • Board contains only X and O.

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"]]

Explanation:

The middle region is fully surrounded and gets captured.

Example 2:

Input:

board = [["X"]]

Output:

[["X"]]

Explanation:

A single border cell cannot be surrounded.

Example 3:

Input:

board = [["O","O"],["O","O"]]

Output:

[["O","O"],["O","O"]]

Explanation:

All O cells touch the border directly or indirectly.

Loading...
Surrounded Regions - Graph Traversal DSA Problem