AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Surrounded Regions

The key idea

An 'O' survives only if it is connected to the border. So flip the problem: find every border-connected 'O' and protect it, then capture all the rest. Search inward FROM the edges instead of testing each region for the absence of an escape.

Problem

You are given an m x n matrix board containing the characters 'X' and 'O'. Capture every region that is surrounded by 'X'.

A region is captured by flipping all 'O' cells into 'X' cells in that surrounded region. A cell is part of a surrounded region only if it is enclosed — an 'O' that is connected, 4-directionally, to any 'O' on the border of the board is not captured. Modify the board in place: every enclosed 'O' becomes 'X', and every border-connected 'O' stays 'O'.

Constraints

Examples

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"]]
Input: board = [["X"]] Output: [["X"]]

Complexity

Time: O(m * n) Space: O(m * n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems