Surrounded Regions (LeetCode 130): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Union Find
Matrix

You get a board of 'X' and 'O' cells. Any group of connected 'O' cells that is fully enclosed by 'X' should be flipped to 'X'. Groups that touch the edge of the board, directly or through other 'O' cells, are not enclosed and stay as they are.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The direct reading of the problem is to look at each region of 'O' cells, flood fill it, and decide whether any of its cells sit on the border. If none do, flip the whole region. That is correct but awkward, because you have to explore a region completely before you know whether to flip it, which means either two passes per region or storing the cells you visited.

The cleaner idea is to flip the question around. Instead of asking which regions are surrounded, ask which 'O' cells are safe. A cell is safe exactly when it connects to the border. So start a flood fill from every 'O' on the border, and mark everything it reaches with a temporary symbol such as 'T'. Those are all the cells that survive.

After that, every 'O' still on the board must be enclosed, because the border search would have reached it otherwise. A single final pass flips the remaining 'O' cells to 'X' and turns the 'T' marks back into 'O'. Each cell is touched a constant number of times, and the board itself doubles as the visited set.

Approach: Border DFS with a temporary marker

  1. If the board is empty, return. Otherwise record its dimensions m and n.
  2. Define dfs(r, c) that returns if the cell is out of bounds or not 'O', and otherwise sets it to 'T' and recurses into its four neighbors.
  3. Call dfs on every cell of the first and last column.
  4. Call dfs on every cell of the first and last row. After these calls, every border-connected 'O' is now 'T'.
  5. Scan the whole board. Change each remaining 'O' to 'X', because it was not reachable from the edge.
  6. In the same scan, change each 'T' back to 'O', restoring the safe regions.

Step-by-step example

board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
  1. The column pass calls dfs on (r,0) and (r,3) for every row. All eight of those cells are 'X', so nothing changes.
  2. The row pass reaches (3,1), which is 'O' on the bottom edge. It becomes 'T'. Its neighbors (2,1), (3,0) and (3,2) are all 'X', and (4,1) is out of bounds, so the fill stops there.
  3. The interior cells (1,1), (1,2) and (2,2) are still 'O' because no border fill reached them.
  4. The final scan flips those three cells to 'X' and turns (3,1) back into 'O'. The only 'O' left is the one on the bottom edge.

Code: Python, Java, C++

1class Solution:
2    def solve(self, board: List[List[str]]) -> None:
3        if not board: return
4        m, n = len(board), len(board[0])
5
6        def dfs(r, c):
7            if r < 0 or r >= m or c < 0 or c >= n or board[r][c] != 'O':
8                return
9            board[r][c] = 'T'  # Temporarily mark
10            dfs(r + 1, c)
11            dfs(r - 1, c)
12            dfs(r, c + 1)
13            dfs(r, c - 1)
14
15        # Mark border-connected O's
16        for r in range(m):
17            dfs(r, 0)
18            dfs(r, n - 1)
19        for c in range(n):
20            dfs(0, c)
21            dfs(m - 1, c)
22
23        # Flip: O->X, T->O
24        for r in range(m):
25            for c in range(n):
26                if board[r][c] == 'O':
27                    board[r][c] = 'X'
28                elif board[r][c] == 'T':
29                    board[r][c] = 'O'

Time and space complexity

Time

O(m × n)

Each border call is O(1) unless it hits an 'O', and every 'O' is converted to 'T' at most once, so the total DFS work is proportional to the number of cells. The final pass reads each cell once more.

Space

O(m × n)

No extra arrays are allocated, but the recursion stack can grow as deep as the largest border-connected region, which is the whole board in the worst case.

Other approaches

BFS from the border (time O(m × n), space O(m × n))

Push all border 'O' cells into a queue, mark them, and expand with a standard BFS. It does the same work as the DFS but uses an explicit queue, which avoids recursion depth limits on a 200 by 200 board.

Union-Find with a dummy border node (time O(m × n × α(m × n)), space O(m × n))

Union every border 'O' with a virtual node and every pair of adjacent 'O' cells with each other. Afterwards, any 'O' not connected to the virtual node gets flipped. It is heavier to write but generalizes well when connectivity changes over time.

Common mistakes

  • Flipping regions while exploring them from the inside. You cannot know a region is enclosed until it has been fully explored, which is why searching from the border is simpler.
  • Marking border cells as 'X' or skipping the temporary marker. Without a third symbol you cannot tell surviving 'O' cells from enclosed ones in the final pass.
  • Hitting the recursion limit. A board of 200 by 200 can produce a chain of 40,000 recursive calls, which exceeds Python's default limit, so raise the limit or switch to an iterative BFS.
  • Treating diagonal neighbors as connected. Only the four orthogonal directions count here.

Frequently asked questions

Why start from the border in Surrounded Regions?

Cells that reach the border are the exceptions that must not flip, and they are easy to find by searching outward from the edge. Everything the border search misses is automatically surrounded, so one search answers the question for every region at once.

Is DFS or BFS better for Surrounded Regions?

Both visit each cell once and run in O(m × n). Recursive DFS is shorter to write, while BFS uses an explicit queue and is safer on large boards where deep recursion could overflow the stack.

Can Surrounded Regions be solved in O(1) extra space?

The marking itself uses no extra memory because the board stores the state. The only extra cost is the search structure, recursion stack or queue, so a true O(1) solution would need an approach that avoids explicit traversal, which is not practical here.

What is the time complexity of Surrounded Regions?

It is O(m × n). Every cell is visited a constant number of times across the border searches and the final flip pass.