Original title Address
1. Replace All "O" with the border with other characters, such as "#"
2. Replace all remaining "O" with "X"
3. Replace All "#" with the border with "X"
Code:
1 voidReplace (vector<vector<Char> > &board,intIintJCharBefore,CharAfter ) {2stack<pair<int,int> >St;3 intRlen =board.size ();4 intClen = board[0].size ();5 intrnext[4] = {-1,1,0,0};6 intcnext[4] = {0,0, -1,1};7 8St.push (pair<int,int>(i, J));9 while(!St.empty ()) {Tenpair<int,int> top =st.top (); One St.pop (); A if(Top.first <0|| Top.first >= Rlen | | Top.second <0|| Top.second >= Clen | | Board[top.first][top.second]! =before) - Continue; -Board[top.first][top.second] =After ; the for(intK =0; K <4; k++) -St.push (pair<int,int> (Top.first + rnext[k], Top.second +cnext[k])); - } - } + - voidSolve (vector<vector<Char>> &Board) { + if(Board.empty () | | board[0].empty ())return; A intRlen =board.size (); at intClen = board[0].size (); - - for(inti =0; i < Rlen; i++) { -Replace (board, I,0,'O','#'); -Replace (board, I, Clen-1,'O','#'); - } in for(intj =0; J < Clen; J + +) { -Replace (board,0J'O','#'); toReplace (board, Rlen-1J'O','#'); + } - the for(inti =1; I < Rlen-1; i++) * for(intj =1; J < Clen-1; J + +) $ if(Board[i][j] = ='O')Panax NotoginsengBOARD[I][J] ='X'; - the for(inti =0; i < Rlen; i++) { +Replace (board, I,0,'#','O'); AReplace (board, I, Clen-1,'#','O'); the } + for(intj =0; J < Clen; J + +) { -Replace (board,0J'#','O'); $Replace (board, Rlen-1J'#','O'); $ } -}
At first it was replaced with a recursive return, the result exploded stack (Runtime error), had to honestly use the stack.
LEETCODE#130 surrounded regions