130. Surrounded Regions

https://leetcode.com/problems/surrounded-regions/

Problem

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Solution

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.size() < 3 || board[0].size() < 3) return;
        const int w = board[0].size();
        const int h = board.size();
        for (int i = 0; i < w; ++i) {
            flip(board, 0, i);
            flip(board, h - 1, i);
        }
        
        for (int i = 1; i < h - 1; ++i) {
            flip(board, i, 0);
            flip(board, i, w - 1);
        }
        
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                if (board[i][j] == 'N') board[i][j] = 'O';
                else if (board[i][j] == 'O') board[i][j] = 'X';
            }
        }
    }
    void flip(vector<vector<char>>& board, int row, int col) {
        const int w = board[0].size();
        const int h = board.size();
        if (row < 0 || row >= h || col < 0 || col >= w) return;
        if (board[row][col] == 'X' || board[row][col] == 'N') return;
        board[row][col] = 'N';
        flip(board, row + 1, col);
        flip(board, row - 1, col);
        flip(board, row, col + 1);
        flip(board, row, col - 1);
    }
};
  • #dfs

Last updated

Was this helpful?