Surrounded Regions

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region. An 'O' on the border of the board (or connected to a border 'O') is not surrounded and should not be flipped.

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 'O' at position (3,1) is on the border and is not surrounded. The 'O's at (1,1), (1,2), and (2,2) are surrounded by 'X' on all sides, so they are captured and flipped to 'X'.

Example 2:

Input: board = [["X"]]

Output: [["X"]]

Explanation: There are no 'O' cells to capture.

Example 3:

Input: board = [["O","O"],["O","O"]]

Output: [["O","O"],["O","O"]]

Explanation: All 'O's are on the border or connected to a border 'O', so none are captured.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'
Source: Graphs pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle