Surrounded Regions [LeetCode]
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 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
Solution: Scans from edges of the board, if the char is 'O', mark it as '1', then search four char around it, until no 'O' is got. Finally, scan all char in board, if '1', replace with 'O'; if 'O', replace with 'X'.
1 void searchMark(int x, int y, vector<vector<char>> &board){ 2 if(x < 0 || x >= board.size() || y < 0 || y >= board[x].size()) 3 return; 4 if(board[x][y] == 'O'){ 5 board[x][y] = '1'; 6 searchMark(x, y - 1, board); 7 searchMark(x, y + 1, board); 8 searchMark(x + 1, y, board); 9 searchMark(x - 1, y, board); 10 } 11 } 12 13 void solve(vector<vector<char>> &board) { 14 int row = board.size(); 15 if(row <= 2) 16 return; 17 int column = board[0].size(); 18 if(column <= 2) 19 return; 20 21 //top 22 for(int i = 0; i < column; i ++){ 23 if(board[0][i] == 'O') 24 searchMark(0, i, board); 25 } 26 //bottom 27 int bottom_idx = row - 1; 28 for(int i = 0; i < column; i ++){ 29 if(board[bottom_idx][i] == 'O') 30 searchMark(bottom_idx, i, board); 31 } 32 //left 33 for(int i = 1; i < row - 1; i++){ 34 if(board[i][0] == 'O') 35 searchMark(i, 0, board); 36 } 37 //right 38 for(int i = 1; i < row - 1; i++){ 39 if(board[i][column - 1] == 'O') 40 searchMark(i, column - 1, board); 41 } 42 43 for(int i = 0; i < row; i ++){ 44 for(int j = 0; j < column; j ++){ 45 if(board[i][j] == '1'){ 46 board[i][j] = 'O'; 47 }else if(board[i][j] == 'O'){ 48 board[i][j] = 'X'; 49 } 50 } 51 52 } 53 }