problem-solving idea: The key point is to find that all the points that are not surrounded are connected to the "O" point on the boundary.
Give a two-dimensional matrix that contains ' x ' and ' O ', find all the areas surrounded by ' x ' and fill it with ' X '. Have you ever encountered this problem in a real interview? Yes sample
Give the two-dimensional matrix:
x x x x x
o o x x x
o x
x o x x
Fills the area surrounded by ' X ' into:
x x x x x x x x x × x x x O x x
Label Union Find width First search
Class Solution {public:/* * @param board:board a 2D board containing ' X ' and ' O ' * @return: Nothing */void Surroundedregions (vector<vector<char>> &board) {//write your code here if (b
Oard.empty ()) return;
int row=board.size (), col=board[0].size ();
cout<<row<<col<<endl; The first line for (int i=0;i<row;i++) {for (int j=0;j<col;j++) {if (i==0| | i==row-1| | j==0| |
J==COL-1) &&board[i][j]== ' O ') {board[i][j]= ' F ';
Stack<int> row1,col1;
Row1.push (i);
Col1.push (j);
while (!row1.empty ()) {int tempr=row1.top (), Tempc=col1.top ();
Col1.pop ();
Row1.pop ();
if (tempr-1>=0&&board[tempr-1][tempc]== ' O ') {board[tempr-1][tempc]= ' F ';
Row1.push (tempR-1); Col1.push (TEMPC); } if (tempr+1<row&&board[tempr+1][tempc]== ' O ') {board[tempr+1][tempc]= ' F
';
Row1.push (tempr+1);
Col1.push (TEMPC); } if (tempc-1>-1&&board[tempr][tempc-1]== ' O ') {board[tempr][tempc-1]= ' F '
;
Row1.push (TEMPR);
Col1.push (tempC-1); } if (tempc+1<col&&board[tempr][tempc+1]== ' O ') {board[tempr][tempc+1]= ' F
';
Row1.push (TEMPR);
Col1.push (tempc+1);
}}}}} for (int i=0;i<row;i++) {
for (int j=0;j<col;j++) {if (board[i][j]== ' O ') board[i][j]= ' X '; }} for (int i=0;i<row;i++) {for (int j=0;j<col;j++) {if (board[i][j]== ' F ') board[i][j]= ' O '; }
}
}
};