problem:
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 X O X X
Hide Tags
题意:将被X包围的O换成X
thinking:
(1)首先我用递归做的,提交栈溢出了....
(2)参考网上的实现,要用到一种图形学的算法:泛洪算法-维基
采用BFS或者DFS,使用queue或者stack结构。
code:
class Solution { public: int row; int col; void bfs(vector<vector<char> > &board, int r, int c) { queue<pair<int, int> > qe; qe.push({r, c}); while(!qe.empty()) { r = qe.front().first; c = qe.front().second; qe.pop(); if (r>0&&board[r-1][c]=='O') { board[r-1][c] = '+'; qe.push({r-1,c}); } if (r+1<row&&board[r+1][c]=='O') { board[r+1][c] = '+'; qe.push({r+1,c}); } if (c>0&&board[r][c-1]=='O') { board[r][c-1] = '+'; qe.push({r,c-1}); } if (c+1<col&&board[r][c+1]=='O') { board[r][c+1] = '+'; qe.push({r,c+1}); } } return; } void solve(vector<vector<char> > &board) { if (board.empty()) return; row = board.size(); col = board[0].size(); // top edge for(int i = 0; i < col; ) { if(board[0][i] == 'O') { int j=i; while(board[0][j]=='O') j++; board[0][i] = '+'; bfs(board, 0, i); i = j; } else i++; } // bottom edge for(int i = 0; i < col;) { if(board[row-1][i] == 'O') { int j=i; while(board[row-1][j]=='O') j++; board[row-1][i] = '+'; bfs(board, row-1, i); i = j; } else i++; } // left edge for(int i = 1; i < row-1;) { if(board[i][0] == 'O') { int j=i; while(board[j][0]=='O') j++; board[i][0] = '+'; bfs(board, i, 0); i = j; } else i++; } // right edge for(int i = 1; i < row-1; ) { if(board[i][col-1] == 'O') { int j=i; while(board[j][col-1]=='O') j++; board[i][col-1] = '+'; bfs(board, i, col-1); i = j; } else i++; } // then scan all the cells, recover live cells and flip dead cells for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) board[i][j] = (board[i][j]=='+')?'O':'X'; return; } };
时间: 2024-10-15 18:18:18