Surrounded Regions

Pattern: Grid graphs

medium

An O region is captured unless it touches the border. Mark every O reachable from a border O as safe, then turn the remaining O's into X's and the safe ones back into O's.

The problem

Given a board of 'X' and 'O', capture every region of 'O' that is completely surrounded by 'X' (not connected to the border) by flipping it to 'X'. Change the board in place; the tests print it.

Think first

  • Which O regions survive?
  • Is it easier to find surrounded regions or safe ones?
  • How do you remember which O's are safe?

Hints

    Brute force, and why it fails

    For every O region, check whether it reaches the border: O((R × C)²) if done per cell.

    The key insight

    One search from the border finds every safe O; everything else is captured.

    Dry run

    Board XXXX / XOOX / XXOX / XOXX. The O at (3, 1) is on the border: safe.

    Step 1 of 3

    The plan

    mark every O joined to a border O as S
    for each cell: S -> O, O -> X
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    Each cell is visited at most twice.

    Edge cases

    • A 1 × 1 grid.
    • A grid with no land (or no walls).
    • Everything connected.
    I've built my logic, show the code

    Java

    class Solution {
        public void solve(char[][] board) {
            int R = board.length, C = board[0].length;
            for (int r = 0; r < R; r++) { keep(board, r, 0); keep(board, r, C - 1); }   // O's joined to the border survive
            for (int c = 0; c < C; c++) { keep(board, 0, c); keep(board, R - 1, c); }
            for (char[] row : board)
                for (int c = 0; c < C; c++) row[c] = row[c] == 'S' ? 'O' : 'X';   // everything else is captured
        }
    
        private void keep(char[][] b, int r, int c) {
            if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != 'O') return;
            b[r][c] = 'S';                          // safe
            keep(b, r + 1, c); keep(b, r - 1, c); keep(b, r, c + 1); keep(b, r, c - 1);
        }
    }

    C++

    class Solution {
    public:
        void solve(vector<vector<char>>& board) {
            int R = static_cast<int>(board.size()), C = static_cast<int>(board[0].size());
            for (int r = 0; r < R; r++) { keep(board, r, 0); keep(board, r, C - 1); }   // O's joined to the border survive
            for (int c = 0; c < C; c++) { keep(board, 0, c); keep(board, R - 1, c); }
            for (vector<char>& row : board)
                for (int c = 0; c < C; c++) row[c] = row[c] == 'S' ? 'O' : 'X';   // everything else is captured
        }
    
        void keep(vector<vector<char>>& b, int r, int c) {
            if (r < 0 || c < 0 || r >= static_cast<int>(b.size()) || c >= static_cast<int>(b[0].size()) || b[r][c] != 'O') return;
            b[r][c] = 'S';                          // safe
            keep(b, r + 1, c); keep(b, r - 1, c); keep(b, r, c + 1); keep(b, r, c - 1);
        }
    };

    Python

    class Solution:
        def solve(self, board: list[list[str]]) -> None:
            R, C = len(board), len(board[0])
            st = [(r, c) for r in range(R) for c in range(C) if (r in (0, R - 1) or c in (0, C - 1)) and board[r][c] == "O"]
            for r, c in st:
                board[r][c] = "S"                   # O's joined to the border are safe
            while st:
                r, c = st.pop()
                for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= x < R and 0 <= y < C and board[x][y] == "O":
                        board[x][y] = "S"
                        st.append((x, y))
            for row in board:
                for c in range(C):
                    row[c] = "O" if row[c] == "S" else "X"   # everything else is captured

    Common mistakes

    • Capturing O's on the border.
    • Forgetting to change the temporary marks back.

    Similar problems