链接:https://oj.leetcode.com/problems/surrounded-regions/
描述:
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
解法一:
本体开始一直在想着怎么找到所有的包围O的环,想了很久没想出来。
后面从分析怎样的O不需要flip,就有了解法。
第一个是dfs递归的,提交是Runtime error,应该是栈溢出的问题。
代码如下:
void dfs(vector<vector<char>> &board, int i, int j)
{
int m = board.size();
int n = board.at(0).size();
if( i < 0 || i >= m ||
j < 0 || j >= n ||
board[i][j] != 'O')
return;
board[i][j] = 'E';
dfs(board, i-1, j);
dfs(board, i+1, j);
dfs(board, i, j-1);
dfs(board, i, j + 1);
}
void solve(vector<vector<char>> &board)
{
int m= board.size();
if( m <= 0) return;
int n = board.at(0).size();
for(int i= 0; i < m; ++i)
{
dfs(board, i, 0);
dfs(board, i, n - 1);
}
for(int i=0; i < n; ++i)
{
dfs(board, 0, i);
dfs(board, m-1, i);
}
for(int i=0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if( board[i][j] == 'O')
board[i][j] = 'X';
else if(board[i][j] == 'E')
board[i][j] = 'O';
}
}
}
方法二:
非递归版的,用stack实现,用到一个技巧:怎么用一个数存储坐标的i和j两个值。
代码如下:
void dfs2(vector<vector<char>> &board, int i, int j)
{
if( board[i][j] != 'O' )
return;
int m= board.size();
int n = board[0].size();
int big = max(m, n);
stack<int> q;
q.push(i * big + j);
int next[4][2] = { -1, 0, 1, 0, 0, -1, 0, 1};
while(!q.empty())
{
int num = q.top();
q.pop();
int curI = num/big;
int curJ = num%big;
board[curI][curJ] = 'E';
for(int count=0; count < 4; ++count)
{
int nextI = curI + next[count][0];
int nextJ = curJ + next[count][1];
if( nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n ||
board[nextI][nextJ] != 'O')
continue;
q.push(nextI * big + nextJ);
}
}
}
void solve(vector<vector<char>> &board)
{
int m= board.size();
if( m <= 0) return;
int n = board.at(0).size();
for(int i= 0; i < m; ++i)
{
dfs2(board, i, 0);
dfs2(board, i, n - 1);
}
for(int i=0; i < n; ++i)
{
dfs2(board, 0, i);
dfs2(board, m-1, i);
}
for(int i=0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if( board[i][j] == 'O')
board[i][j] = 'X';
else if(board[i][j] == 'E')
board[i][j] = 'O';
}
}
}