Surrounded Regions

Medium

Topics
GraphDFSBFSMatrix

Given an m x n board of 'X' and 'O', capture all regions of 'O' that are fully surrounded by 'X' (flip them to 'X'). Any 'O' connected to the border is safe. Return the resulting board.

Example 1

0XXXX1XOOX2XXOX3XOXX0123
captured — becomes Xescapes via the border — stays O
A region of Os is captured only when it is fenced in by X on all four sides. Any region touching the border has an escape route and survives, which is why the trick is to flood inward from the edges rather than search each region.
Character grid — one row per line.
Input:  board = ["XXXX","XOOX","XXOX","XOXX"]
Output: ["XXXX","XXXX","XXXX","XOXX"]

Constraints

  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

An ‘O’ survives only if it can reach the border. So mark every border-connected ‘O’ as safe first; then every remaining ‘O’ is surrounded and gets flipped.

Approach

  1. DFS/BFS from every ‘O’ on the border, marking reachable ‘O’s as safe (temporary marker).
  2. Scan the board: flip unmarked ‘O’ to ‘X’.
  3. Restore the safe markers back to ‘O’.

Dry Run

board  X X X X
       X O O X
       X X O X
       X O X X
Rather than asking "is this region surrounded?", invert it: flood inward from every
border O and mark whatever is reachable as safe.
  the only O on the border is at (3,1), and it has no O neighbours
  after flooding:
       X X X X
       X O O X
       X X O X
       X # X X
  now one pass rewrites the board: every remaining O is captured, every # is safe
final  X X X X
       X X X X
       X X X X
       X O X X
answer the three interior Os are captured; the border-connected one survives
The two-phase shape is the whole idea, and it is the standard move when a local
test is hard but its complement is easy. Deciding capture cell by cell needs
global information -- whether ANY path to the edge exists -- whereas reachability
from the edge is a plain flood fill.
The temporary '#' is what carries information between the phases. It cannot be 'X'
(the rewrite pass would not know to restore it) and it cannot stay 'O' (the rewrite
pass would capture it).
On OOO / OXO / OOO every O is border-connected, so nothing is captured and the
board comes back unchanged -- the case that catches an implementation which
assumes something must be surrounded.
One frame per cell again: with the default recursion limit of 1000, a 32 x 32
all-O grid overflows while 30 x 30 passes, which is why this page raises the
limit for its tests.

Complexity

  • Time — O(m*n): each cell visited a constant number of times.
  • Space — O(m*n): recursion/queue worst case.

Common Pitfalls

  • Mark border-safe cells first; deciding capture per-cell without that global info is wrong.
  • The recursive flood fill costs one stack frame per cell, so a single component of k cells is k frames deep. At the stated limit of 300 x 300 that is 90000 frames for an all-land grid. This page raises Python's recursion limit so the tests can run; with the default limit of 1000, a 32 x 32 all-land grid already raises RecursionError while 30 x 30 still passes. Say so, and offer the explicit-stack version that sinks on push.

Full Solution — all languages

class Solution:
    def solve(self, board):
        if not board: return
        R,C=len(board),len(board[0])
        def dfs(r,c):
            if r<0 or r>=R or c<0 or c>=C or board[r][c]!='O': return
            board[r][c]='#'
            dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1)
        for r in range(R):
            dfs(r,0); dfs(r,C-1)
        for c in range(C):
            dfs(0,c); dfs(R-1,c)
        for r in range(R):
            for c in range(C):
                if board[r][c]=='O': board[r][c]='X'
                elif board[r][c]=='#': board[r][c]='O'
SensAI
Beta
Tap the mic to stop voice mode