This problem was not quite difficult (a typical BFS traversal of graph), though, its aceptance rate was relatively low. In fact, the key obstacle in passing this problem are how to reduce the number of checks and avoid the annoying TLE.
There is a nice idea on this link. In fact, all the surrounded regions would not contain a O on the boundary. This idea takes advantage of this observation and visit the board from O' s on the boundary and mark them Using another character, say, #. Finally, all the remaining O' s is the surrounded regions and should is captured to X. The # regions simply need to being recovered to O.
I adopt the idea from the above link. And I include some minor optimizations. For example, I pass the "queue tovisit to the" Update function to check and update the four neighbors Toge ther during the BFS. This turns-to-reduce the running time from 28ms to 16ms.
The code is as follows.
1 classSolution {2 Public:3 voidSolve (vector<vector<Char>>&Board) {4 if(Board.empty ())return;5 intm = Board.size (), n = board[0].size ();6 for(inti =0; I < m; i++) {7 if(board[i][0] =='O')8Mark (Board, I,0);9 if(Board[i][n-1] =='O')TenMark (Board, I, N-1); One } A for(intj =0; J < N; J + +) { - if(board[0][J] = ='O') -Mark (board,0, j); the if(Board[m-1][J] = ='O') -Mark (board, M-1, j); - } - Capture (board); + } - Private: + //Update Neighbors A voidUpdate (vector<vector<Char>>& board, queue<pair<int,int>>& Tovisit,intRintc) { at intm = Board.size (), n = board[0].size (); - if(R-1>=0&& Board[r-1][C] = ='O') { -Board[r-1][C] ='#'; -Tovisit.push (Make_pair (R-1, c)); - } - if(R +1< m && Board[r +1][C] = ='O') { inBoard[r +1][C] ='#'; -Tovisit.push (Make_pair (R +1, c)); to } + ifC1>=0&& Board[r][c-1] =='O') { -Board[r][c-1] ='#'; theTovisit.push (Make_pair (R, C-1)); * } $ if(C +1< n && Board[r][c +1] =='O') {Panax NotoginsengBoard[r][c +1] ='#'; -Tovisit.push (Make_pair (R, C +1)); the } + } A //Mark non-surrounded Regions the voidMark (vector<vector<Char>>& Board,intRintc) { +queue<pair<int,int> >tovisit; - Tovisit.push (Make_pair (R, c)); $BOARD[R][C] ='#'; $ while(!Tovisit.empty ()) { - intnum =tovisit.size (); - for(inti =0; i < num; i++) { thepair<int,int> cur =Tovisit.front (); - Tovisit.pop ();Wuyi Update (board, Tovisit, Cur.first, cur.second); the } - } Wu } - //Capture surrounded Regions About voidCapture (vector<vector<Char>>&Board) { $ intm = Board.size (), n = board[0].size (); - for(inti =0; I < m; i++) { - for(intj =0; J < N; J + +) { - if(Board[i][j] = ='#') ABOARD[I][J] ='O'; + ElseBOARD[I][J] ='X'; the } - } $ } the};
[Leetcode] Surrounded regions