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
这题对速度还是有要求的,所以只能从四条边往里面找。想用偷懒逐行扫描是不行的!
class Solution {
public:
int dimy;
int dimx;
void travelling(int dy, int dx, vector<vector<char>> &board) {
if(board[dy][dx] == 'X') return;
queue<pair<int, int>> thequeue;
thequeue.push(make_pair(dy, dx));
while(!thequeue.empty()) {
pair<int, int> front = thequeue.front();
thequeue.pop();
board[front.first][front.second] = 'Z';
if(front.first > 0 && board[front.first - 1][front.second] == 'O') {
board[front.first - 1][front.second] = 'Z';
thequeue.push(make_pair(front.first - 1, front.second));
}
if(front.first < dimy - 1 && board[front.first + 1][front.second] == 'O') {
board[front.first][front.second] = 'Z';
thequeue.push(make_pair(front.first + 1, front.second));
}
if(front.second > 0 && board[front.first][front.second - 1] == 'O') {
board[front.first][front.second - 1] = 'Z';
thequeue.push(make_pair(front.first, front.second - 1));
}
if(front.second < dimx - 1 && board[front.first][front.second + 1] == 'O') {
board[front.first][front.second + 1] = 'Z';
thequeue.push(make_pair(front.first, front.second + 1));
}
}
}
void solve(vector<vector<char>> &board) {
dimy = board.size();
if(dimy == 0) return;
dimx = board[0].size();
if(dimx == 0) return;
for(int ii = 0; ii < dimy; ii ++) {
travelling(ii, 0, board);
travelling(ii, dimx - 1, board);
}
for(int ii = 0; ii < dimx; ii ++) {
travelling(0, ii, board);
travelling(dimy - 1, ii, board);
}
for(int ii = 0; ii < dimy; ii ++) {
for(int jj = 0; jj < dimx; jj ++) {
board[ii][jj] = board[ii][jj] == 'Z' ? 'O' : 'X';
}
}
}
};