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 XAfter running your function, the board should be:
X X X X X X X X X X X X X O X X
思路:这道题的要求是边界相连的O不动,被围在里面的O变为X。这里有个trick,就是先把边界相连的O变为另一个符号#,然后遍历矩阵,把#变回O,同时把O变为X,就可以了。找所有的边界O需要用到dfs,只对所有边界元素遍历,这里的特殊之处在于遇到X或者#都直接返回,只有遇到O才加以处理并继续DFS,因此不需要另外使用map判定条件了。
- #depth-first-search and change boundary O's to #'s.
- void dfs(vector<vector<char>> &board, int i, int j){
- if(board[i][j] == 'X' || board[i][j] == '#') return;
- board[i][j] = '#';
- if(i > 0) dfs(board,i-1,j);
- if(i < board.size()-1) dfs(board,i+1,j);
- if(j > 0) dfs(board,i,j-1);
- if(j < board[0].size() - 1) dfs(board,i,j+1);
- }
- void solve(vector<vector<char>> &board) {
- if(board.empty()) return;
- #r is row number, c is column numer
- int r = board.size(), c = board[0].size();
- #do dfs on the boundary lines
- for(int i = 0; i < c; i++){
- dfs(board,0,i);
- dfs(board,r-1,i);
- }
- for(int j = 1; j < r-1; j++){
- dfs(board,j,0);
- dfs(board,j,c-1);
- }
- #change #'s back to O's, change O's to X's
- for(int i = 0; i < r; i++){
- for(int j = 0; j < c; j++){
- if(board[i][j] == '#') board[i][j] = 'O';
- else if(board[i][j] == 'O') board[i][j] = 'X';
- }
- }
- }
No comments:
Post a Comment