Surrounded Regions

来源:互联网 发布:2017中国十大网络主播 编辑:程序博客网 时间:2024/05/23 19:09

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
#include<iostream>#include<vector>#include<queue>using namespace std;struct point{int x;int y;point(int idx,int idy):x(idx),y(idy){}};queue<point*> Q;void IsCircle(int high,int row,vector<vector<char>> &board){if (high>=0&&high<board.size()&&row>=0&&row<board[0].size()&&board[high][row]=='O'){board[high][row]='L';Q.push(new point(high,row));}}void BFS(int high,int row,vector<vector<char>> &board){IsCircle(high,row,board);while (!Q.empty()){point* p = Q.front();Q.pop();IsCircle((p->x)+1,p->y,board);IsCircle((p->x)-1,p->y,board);IsCircle(p->x,p->y+1,board);IsCircle(p->x,p->y-1,board);}}void solve(vector<vector<char>> &board) { if (board.empty() || board[0].size() == 0) {  return;  }  int high = board.size();int row  = board[0].size();for (int x = 0;x!=row;++x){BFS(0,x,board);BFS(high-1,x,board);}for (int y = 0;y!=high;++y){BFS(y,0,board);BFS(y,row-1,board);}for (int i=0;i!=high;++i){for (int j=0;j!=row;++j ){board[i][j]=board[i][j]=='L'?'O':'X';}}}


 

 

0 0