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
这道题是修改被'X'包围的区域,题目难度为Medium。
能够通向四个边框的‘O’是没被‘X’包围的,不能通向边框的‘O’则是被‘X’包围的,因此可以通过遍历四个边框上的位置,采用深度优先搜索的策略将没被包围的‘O’替换为‘#’,最后遍历整个board,将‘O’(被包围的‘O’)替换为‘X’,将‘#’(没被包围的‘O’)替换为‘O’。具体代码:
class Solution {
void dfs(vector<vector<char>>& board, int r, int c) {
if(board[r][c] == 'O') {
board[r][c] = '#';
if(r>0) dfs(board, r-1, c);
if(r<board.size()-1) dfs(board, r+1, c);
if(c>0) dfs(board, r, c-1);
if(c<board[0].size()-1) dfs(board, r, c+1);
}
}
public:
void solve(vector<vector<char>>& board) {
int row = board.size();
if(!row) return;
int col = board[0].size();
if(!col) return;
for(int i=0; i<col; ++i) {
dfs(board, 0, i);
dfs(board, row-1, i);
}
for(int i=1; i<row-1; ++i) {
dfs(board, i, 0);
dfs(board, i, col-1);
}
for(int i=0; i<row; ++i) {
for(int j=0; j<col; ++j) {
if(board[i][j] == 'O') board[i][j] = 'X';
else if(board[i][j] == '#') board[i][j] = 'O';
}
}
}
};
提交之后报了 Runtime Error,一直找不到原因,看了讨论原来是栈溢出了,难怪这道题通过率这么低。。在大集合测试时递归工作栈深度太深导致溢出,所以在递归函数中修改了深度优先搜索的判断条件,将四个边框上位置的搜索放在solve函数的for循环中来处理,在递归函数中就不处理他们了,这样一定程度上降低了递归工作栈的深度,提交通过。具体代码:
class Solution {
void dfs(vector<vector<char>>& board, int r, int c) {
if(board[r][c] == 'O') {
board[r][c] = '#';
if(r>1) dfs(board, r-1, c);
if(r+2<board.size()) dfs(board, r+1, c);
if(c>1) dfs(board, r, c-1);
if(c+2<board[0].size()) dfs(board, r, c+1);
}
}
public:
void solve(vector<vector<char>>& board) {
int row = board.size();
if(!row) return;
int col = board[0].size();
if(!col) return;
for(int i=0; i<col; ++i) {
dfs(board, 0, i);
dfs(board, row-1, i);
}
for(int i=1; i<row-1; ++i) {
dfs(board, i, 0);
dfs(board, i, col-1);
}
for(int i=0; i<row; ++i) {
for(int j=0; j<col; ++j) {
if(board[i][j] == 'O') board[i][j] = 'X';
else if(board[i][j] == '#') board[i][j] = 'O';
}
}
}
};
还可以采用广度优先的策略来解决问题,感兴趣的同学可以自己实现下。