Surrounded Regions

Given a nonempty rectangular matrix mat containing only the characters X and O, return the matrix after replacing every surrounded O with X. O cells connect…

Given a nonempty rectangular matrix mat containing only the characters X and O, return the matrix after replacing every surrounded O with X. O cells connect horizontally or vertically, never diagonally. An O is surrounded exactly when its connected O region does not touch any boundary. Keep every boundary-connected O and every original X unchanged.

- 1 <= N, M <= 300, where N is the row count and M the column count. - Every row has M cells; each cell is exactly the character X or O. - Return a same-shaped nested character matrix. - Visualization presets use at most 12x12 cells; larger valid grids remain coding inputs.

Example 1: input mat = [["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 connected O cells at (1,1), (1,2) and (2,2) are enclosed. The separate O at (3,1) touches the boundary and remains unchanged. Coordinates are zero-based.

Example 2: input mat = [["X","X","X"],["X","O","X"],["X","X","X"]]; output [["X","X","X"],["X","X","X"],["X","X","X"]]. The center O has no four-directional O path to any boundary, so it becomes X.

Category: Graphs. Topic: graph. Difficulty: Medium. Patterns: graph-traversal.