AlgoInsight

DSA problem

Surrounded Regions

MediumDepth First Search (DFS)Pattern: Depth First Search (DFS)top150AmazonMicrosoftGoogleBloombergAdobe

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. A region of 'O's is captured iff and only if it is NOT connected to any 'O' on the BORDER of the board.

The naive approach — scan each 'O' region, then check whether it touches the border — repeats work. A much cleaner inversion is: any 'O' connected to a border 'O' is SAFE, and every other 'O' is captured. So we start from the border and flood-fill outward.

The optimal algorithm is in two passes. First, run DFS from every 'O' on the four borders, marking the entire reachable 'O'-region as a temporary symbol like 'S' (safe). Second, scan the full board: any remaining 'O' is surrounded so flip it to 'X'; any 'S' is safe so revert it back to 'O'. The result is the captured board.

Time is O(m * n) because each cell is touched a constant number of times (border DFS plus final scan). Worst-case recursion depth is O(m * n) on a fully 'O'-board, so auxiliary space is O(m * n) for the stack. Using an iterative stack would not change the asymptotic space.

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 inner Os at (1,1), (1,2), (2,2) are fully surrounded and become X. The O at (3,1) sits on the border and stays.
Example 2
Input: board = [["X"]]
Output: [["X"]]
Explanation: A single-cell board with X is unchanged.
Example 3
Input: board = [["O","O"],["O","O"]]
Output: [["O","O"],["O","O"]]
Explanation: Every O is on the border, so all are safe and the board is unchanged.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dfsmatrixgraphflood-fill

Browse all DSA problems