[LeetCode] Surrounded Regions

来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/06/14 21:19
[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

[Analysis]
广度优先搜索,注意记录状态。

[Solution]

class Solution {
public:
struct Grid{
int x, y;
Grid(int _x, int _y) : x(_x), y(_y){}
};

// BFS
bool BFS(vector<vector<char> > &board, int m, int n, queue<Grid> &myQueue, vector<vector<int> > &visited, int k, vector<Grid> &res){
while(!myQueue.empty()){
Grid grid = myQueue.front();
myQueue.pop();
res.push_back(grid);

// located along the border
if(grid.x == 0 || grid.x == m-1 || grid.y == 0 || grid.y == n-1){
return false;
}

// upper
if(board[grid.x-1][grid.y] == 'O'){
// has been visited in the previous BFS
if(visited[grid.x-1][grid.y] < k){
return false;
}
else if(visited[grid.x-1][grid.y] == m*n){
visited[grid.x-1][grid.y] = k;
myQueue.push(Grid(grid.x-1, grid.y));
}
}

// down
if(board[grid.x+1][grid.y] == 'O'){
// has been visited in the previous BFS
if(visited[grid.x+1][grid.y] < k){
return false;
}
else if(visited[grid.x+1][grid.y] == m*n){
visited[grid.x+1][grid.y] = k;
myQueue.push(Grid(grid.x+1, grid.y));
}
}

// left
if(board[grid.x][grid.y-1] == 'O'){
// has been visited in the previous BFS
if(visited[grid.x][grid.y-1] < k){
return false;
}
else if(visited[grid.x][grid.y-1] == m*n){
visited[grid.x][grid.y-1] = k;
myQueue.push(Grid(grid.x, grid.y-1));
}
}

// right
if(board[grid.x][grid.y+1] == 'O'){
// has been visited in the previous BFS
if(visited[grid.x][grid.y+1] < k){
return false;
}
else if(visited[grid.x][grid.y+1] == m*n){
visited[grid.x][grid.y+1] = k;
myQueue.push(Grid(grid.x, grid.y+1));
}
}
}
return true;
}

void solve(vector<vector<char> > &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// get number of rows
int m = board.size();
if(m == 0){
return;
}

// get number of columns
int n = board[0].size();

// create visited
vector<vector<int> > visited;
for(int i = 0; i < m; ++i){
vector<int> row;
for(int j = 0; j < n; ++j){
row.push_back(m*n);
}
visited.push_back(row);
}

// BFS
int k = 0;
vector<Grid> res;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(board[i][j] == 'O'){
// BFS
res.clear();
queue<Grid> myQueue;
myQueue.push(Grid(i, j));
bool surrounded = BFS(board, m, n, myQueue, visited, k++, res);

// update 'O' into 'X'
if(surrounded){
for(int index = 0; index < res.size(); ++index){
board[res[index].x][res[index].y] = 'X';
}
}
}
}
}
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击