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
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
How
scan the matrix from 1 to size-1.
find a big O ie. 'O'
from this position, do a BFS
mark the position with result.
mark the resulted matrix.
repeat the above until no 'O' is found
replace marked dead 'O' with real 'O'.
My code below is the first glance, never optimized.
Code:
void solve(vector<vector<char> > &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool toBreak = false;
bool isSurrounded = true;
vector<int> processingXs;
vector<int> processingYs;
while(1){
int i=0, sizei=0;;
int j=0, sizej=0;
// Find a big O
for(i=1, sizei=board.size(); i<sizei-1; i++){
for(j=1, sizej=board[i].size();j<sizej-1;j++){
if(board[i][j] == 'O'){
board[i][j] = 1;
processingXs.push_back(i);
processingYs.push_back(j);
toBreak = true;
break;
}
}
if(toBreak){
toBreak = false;
break;
}
}//end find big o
// no big o is found
if(i>=sizei-1){
break;
}
isSurrounded = true;
//find all adjacent big Os and mark them
for(int k=0; k<processingXs.size();k++){
int x=processingXs[k];
int y=processingYs[k];
int left = x-1;
int right = x+1;
int top = y - 1;
int bottom = y + 1;
int cors[][2] = {
{left, y},
{x, top},
{x, bottom},
{right, y},
};
for(int l=0; l<4; l++){
int xx = cors[l][0];
int yy = cors[l][1];
if(board[xx][yy]=='O'){
if(xx>0&&xx<board.size()-1 && yy>0&&yy<board.size()-1){
processingXs.push_back(xx);
processingYs.push_back(yy);
board[xx][yy]='1';
}else{
isSurrounded = false;
}
}
}
}
char symbol = ' ';
if(isSurrounded){
symbol='X';
}else{
symbol='2';
}
for(int l=0; l<processingXs.size(); l++){
int xx = processingXs[l];
int yy = processingYs[l];
board[xx][yy] = symbol;
}
processingXs.clear();
processingYs.clear();
}
for(int xx=0; xx<board.size(); xx++){
for(int yy=0; yy<board.size();yy++){
if(board[xx][yy] == '2'){
board[xx][yy] = 'O';
}
}
}
}