Time Complexity: O (N)
Space complexity: O (N)
Question Analysis:
It is to replace all "O" surrounded by "X" with X. The so-called "encirclement" refers to the four directions of the top, bottom, and left, not including the top and bottom...
Algorithm ideas:
Not surrounded by "X": that is, the connected "O" is connected to the boundary. If you replace the "O" connected to the boundary with *, the other O is replaced with X, finally, restore * to O.
Replace the O connected to the boundary with * using BFs. The specific code is as follows: Time: 52 Ms
/*Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.A region is captured by flipping all 'O's into 'X's in that surrounded region.For example,X X X XX O O XX X O XX O X XAfter running your function, the board should be:X X X XX X X XX X X XX O X X*/class Solution {public:void solve(vector<vector<char>> &board) {int height = board.size(), width;if (height == 0)return;width = board[0].size();//search the 2 colum (the first colum and the last colum)for (int i = 0; i < height; i++){if (board[i][0] == 'O')bfs(i, 0, board);if (board[i][width - 1] == 'O')bfs(i, width - 1, board);}//search the first and last rowsfor (int i = 1; i < width - 1; i++){if (board[0][i] == 'O')bfs(0, i, board);if (board[height - 1][i] == 'O')bfs(height - 1, i, board);}for (int i = 0; i < height; i++){for (int j = 0; j < width; j++){if (board[i][j] == '*'){board[i][j] = 'O';}if (board[i][j] == 'O'){board[i][j] = 'X';}}}}private:struct position{ int x;int y;};void bfs(int x, int y, vector<vector<char>> &board){queue<position>q_pos;visit(x, y, board, q_pos);while (!q_pos.empty()){auto next_pos = q_pos.front();q_pos.pop();visit(x - 1, y, board, q_pos);visit(x + 1, y, board, q_pos);visit(x, y + 1, board, q_pos);visit(x, y - 1, board, q_pos);}}void visit(int x, int y, vector<vector<char>> &board, queue<position> &q_pos){if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] == 'X')return;if (board[x][y] == 'O'){board[x][y] = '*';position p;p.x = x;p.y = y;q_pos.push(p);}}};
Leetcode -- surronded regions