Surrounded Regions

MediumGrid searchLeetCode 130 ↗World 6-8
0:00 / 0:00

Capture every region of O cells walled in by X. Flood fill from the border to mark the O cells that escape; the rest get captured.

▼

The problem

LeetCode 130 (Medium). Given an m × n board of 'X' and 'O', capture every region of 'O' cells that is fully surrounded by 'X' (4-directionally): flip all of its cells to 'X', in place. A region with any cell on the border of the board is not surrounded and stays.

Example (LeetCode's): [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] → [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]: the three O cells in the middle flip; the O on the bottom edge survives.

TRY IT ON LEETCODE ▶

The solution

def solve(board):
    m, n = len(board), len(board[0])
    def mark(r, c):
        if 0 <= r < m and 0 <= c < n and board[r][c] == 'O':
            board[r][c] = 'S'
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                mark(r + dr, c + dc)
    for r in range(m):
        for c in range(n):
            if r in (0, m - 1) or c in (0, n - 1):
                mark(r, c)
    for r in range(m):
        for c in range(n):
            board[r][c] = 'O' if board[r][c] == 'S' else 'X'

Transcript

Surrounded Regions. A board holds X walls and O camps. A group of O cells is surrounded when walls box it in on every side: up, down, left and right. Then it's captured, and every cell in it flips to X. A group that touches the edge can't be surrounded, so it stays.

Here's a four by four board. The three O cells in the middle are walled in on every side, so they're captured and become X. The O on the bottom row sits on the edge, so it survives.

The naive way: from every O, search outward for a path to the edge. That works, but cells in the same group repeat the same search: up to m times n searches, each crossing up to m times n cells.

So flip the question. Don't ask who is trapped. Ask who can escape. Any O that escapes is linked, step by step, to an O on the border. So start at the border, and flood inward from every border O, marking each cell you reach as safe. Whatever the flood never reaches is surrounded.

In code, a helper called mark checks that a cell is on the board and holds an O, renames it S, and recurses into its four neighbors. Call it on every border cell. Then one sweep turns every O left into X, and every S back into O.

Let's run a five by seven board. Walking the border, we find an O on the top edge. The flood follows it down, down, then left: four safe cells. Further on, an O on the left edge floods one neighbor: two more. Now the sweep. A group of three and a lone O were never reached, so they're captured. The six safe cells turn back into O.

Each cell is marked at most once and swept once: order m times n time. The recursion can run as deep as one long, winding region, so space is order m times n too.

Start from the edge, mark who escapes, and capture the rest. That's Surrounded Regions.