Given a 2D board containing 'X' and 'O', capture allregions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's inthat surrounded region.
For example,
Afterrunning your function, the board should be:
分析:
如果某个’O’没有被捕获,那么它有两种情况,位于边界处,或者与边界处的’O’连通。所以我们可以从四个边界上的’O’开始深度搜索,它能到达的’O’都标记为’G’。四个边界都处理完后,再扫描一遍数组,将标记为’G’的都还原为’O’,标记为’O’的更新为’X’。
代码如下:
class Solution {
public:
void solve(vector<vector<char>> &board) {
boundx = board.size();
if (boundx == 0)
return;
boundy = board[0].size();
for (int j = 0; j < boundy; ++j) {
if (board[0][j] == 'O') {
DFS(0, j, board);
}
if (board[boundx-1][j] == 'O') {
DFS(boundx-1, j, board);
}
}
for (int i = 1; i < boundx - 1; ++i) {
if (board[i][0] == 'O') {
DFS(i, 0, board);
}
if (board[i][boundy-1] == 'O') {
DFS(i, boundy-1, board);
}
}
for (int i = 0; i < boundx; ++i) {
for (int j = 0; j < boundy; ++j) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
else if (board[i][j] == 'G')
board[i][j] = 'O';
}
}
return;
}
private:
void DFS(int px, int py, vector<vector<char>> &board) {
int tmpx = px, tmpy = py;
for (int i = 0; i < 4; ++i) {
px += next[i][0];
py += next[i][1];
if (px < 0 || px >= boundx || py >= boundy || py < 0) {
board[tmpx][tmpy] = 'G';
}
else if (board[px][py] == 'O') {
board[px][py] = 'G';
DFS(px, py, board);
}
px = tmpx;
py = tmpy;
}
}
int boundx;
int boundy;
const int next[4][2] = {
{-1, 0},//up
{0, 1}, //right
{1, 0}, //down
{0, -1} //left
};
};
Question:但是上面的代码并不能AC,错误原因是RuntimeError,起初以为可能是给的测试数据不等长,不能构成一个二维数组,所以把该测试用例在自己电脑上跑了一遍,运行没有问题,答案是正确的。不明白LeetCode上是什么情况导致的Runtime Error。请知道的朋友多多指教。