leetcode 130 Surrounded Regions(BFS)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 130 Surrounded Regions(BFS)相关的知识,希望对你有一定的参考价值。

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

题解:这道题测试数据卡的很严。一开始用dfs爆栈了,后来改成bfs又超时了。。最后改进了下:先查边上有没有‘O’,和边上连着的肯定不会被围住。把这些都标记出来以后,剩下的里面的‘O’必然都要变成‘X’。
class Solution {
public:
    int n,m;
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    vector<vector<char> >flag;

    void bfs(vector<vector<char> >& board,int x,int y){
        queue<pair<int,int> >q;
        q.push(make_pair(x,y));
        flag[x][y]=1;
        
        while(!q.empty()){
            int qx=q.front().first;
            int qy=q.front().second;
            q.pop();
            for(int i=0;i<4;i++){
                int tx=qx+dx[i];
                int ty=qy+dy[i];
                if(tx>=0&&tx<n&&ty>=0&&ty<m&&flag[tx][ty]==0&&board[tx][ty]==O){
                    q.push(make_pair(tx,ty));
                    flag[tx][ty]=1;
                }
            }
        }
    }

    void solve(vector<vector<char> >& board) {
        if(board.empty()){
            return ;
        }
        n=board.size();
        m=board[0].size();
        flag.resize(n);
        for(int i=0;i<n;i++){
            flag[i].resize(m,0);
        }
        
        for(int i=0;i<m;i++){
            if(board[0][i]==O&&flag[0][i]==0){
                bfs(board,0,i);
            }
            if(board[n-1][i]==O&&flag[n-1][i]==0){
                bfs(board,n-1,i);
            }
        }
        
        for(int i=1;i<=n-2;i++){
            if(board[i][0]==O&&flag[i][0]==0){
                bfs(board,i,0);
            }
            if(board[i][m-1]==O&&flag[i][m-1]==0){
                bfs(board,i,m-1);
            }
        }
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(board[i][j]==O&&flag[i][j]==0){
                    board[i][j]=X;
                }
            }
        }
    }
};

 

以上是关于leetcode 130 Surrounded Regions(BFS)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(130) Surrounded Regions

LeetCode-130-Surrounded Regions

[LeetCode]130 Surrounded Regions(DFS)

leetcode 130. Surrounded Regions----- java

[LeetCode] 130. Surrounded Regions

一天一道LeetCode#130. Surrounded Regions