[LeetCode] 114: Surrounded Regions

[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 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

[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的博客
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值