SDE & MLE Prep

130. Surrounded Regions

Problem

In a board of 'X' and 'O', flip to 'X' (in place) every region of 'O's that is completely surrounded by 'X's. A region connected (horizontally or vertically) to an 'O' on the border is not surrounded.

Example: ["XXXX","XOOX","XXOX","XOXX"] → ["XXXX","XXXX","XXXX","XOXX"]

An O survives only if connected to the border. Mark border-connected Os as safe (S) via DFS, then flip remaining O → X and S → O.

Complexity: O(R·C).

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        R, C = len(board), len(board[0])

        def mark(r, c):
            if 0 <= r < R and 0 <= c < C and board[r][c] == "O":
                board[r][c] = "S"
                mark(r + 1, c); mark(r - 1, c); mark(r, c + 1); mark(r, c - 1)

        for r in range(R):
            mark(r, 0); mark(r, C - 1)
        for c in range(C):
            mark(0, c); mark(R - 1, c)
        for r in range(R):
            for c in range(C):
                board[r][c] = "O" if board[r][c] == "S" else "X"