广度优先搜索

来源:互联网 发布:低碳钢的弹性模量算法 编辑:程序博客网 时间:2024/06/03 08:10

130. Surrounded Regions

   
Total Accepted: 52330 Total Submissions: 324643 Difficulty: Medium
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
思路:广度优先搜索
我们知道边上的O不可能被包围,和O相通的O也不可能被X包围,我们就是要找出这样的情况并将其他的O设置为X,这些O不变
#include<iostream>#include<vector>#include<queue>using namespace std;void solve(vector<vector<char> >& board) {queue<pair<int,int> > q;int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};if(board.size()==0)return;int lenX = board.size(), lenY = board[0].size();for(int i=0; i<lenX; i++){for(int j=0; j<lenY; j++){if(i==0||i==lenX-1||j==0||j==lenY-1){if(board[i][j]=='O'){q.push(make_pair(i,j));}}}}//BFSwhile(!q.empty()){pair<int,int> p=q.front();q.pop();int indX=p.first;int indY=p.second;board[indX][indY]='Y';for(int i=0;i<4;i++){int newX=indX+dx[i];int newY=indY+dy[i];if(newX>=0&&newX<lenX&&newY>=0&&newY<lenY&&board[newX][newY]=='O'){q.push(make_pair(newX,newY));}}}for(int i=0; i<lenX; i++){for(int j=0; j<lenY; j++){board[i][j]=(board[i][j]=='Y'?'O':'X');}}}int main(){return 0;}



0 0