[LeetCode] 114: Surrounded Regions

来源:互联网 发布:mac图片文件夹在哪里 编辑:程序博客网 时间:2024/05/22 07:58
[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 XX O O XX X O XX O X X

After running your function, the board should be:

X X X XX X X XX X X XX O X X

[Solution]
class Solution {
public:
// BFS
void BFS(vector<vector<char> > &board, queue<pair<int, int> > unSolved, int **used, int m, int n, int depth){
// definition
vector<pair<int, int> > toFill;
int direct[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

// BFS
while(!unSolved.empty()){
// get the head of the queue
toFill.push_back(unSolved.front());
int i = unSolved.front().first;
int j = unSolved.front().second;
unSolved.pop();

// the boder of the board
if(i == 0 || i == m-1 || j == 0 || j == n-1)return;

// move forward
for(int k = 0; k < 4; ++k){
if(board[i+direct[k][0]][j+direct[k][1]] == 'O'){
if(used[i+direct[k][0]][j+direct[k][1]] == -1){
used[i+direct[k][0]][j+direct[k][1]] = depth;
unSolved.push(pair<int, int>(i+direct[k][0], j+direct[k][1]));
}
// has been visited in the previous BFS, and it could not be filled
else if(used[i+direct[k][0]][j+direct[k][1]] < depth){
return;
}
}
}
}
for(int i = 0; i < toFill.size(); ++i){
board[toFill[i].first][toFill[i].second] = 'X';
}
}
// solve
void solve(vector<vector<char> > &board) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// empty board
if(board.size() == 0 || board[0].size() == 0)return;

// initial
int m = board.size(), n = board[0].size();
int **used = new int*[m];
for(int i = 0; i < m; ++i){
used[i] = new int[n];
for(int j = 0; j < n; ++j){
used[i][j] = -1;
}
}

// search
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(board[i][j] == 'O' && used[i][j] == -1){
used[i][j] = i*m + j;
queue<pair<int, int> > unSolved;
unSolved.push(pair<int, int>(i, j));
BFS(board, unSolved, used, m, n, i*m+j);
}
}
}
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击