Surrounded Regions

来源:互联网 发布:龙腾世纪3 捏脸数据 编辑:程序博客网 时间:2024/05/16 18:46

题目:

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

代码如下:

    queue<int> q;
    int n;
    void fill(int x,int y,vector<vector<char>> &board)
    {
        if(x<0||x>=n||y<0||y>=n||board[x][y]!='O')return;
        q.push(x*n+y);
        board[x][y]='D';
    }
    void BFS(int x,int y,vector<vector<char>> &board)
    {
        fill(x,y,board);
        while(q.size()>0)
        {
            int top=q.front();
            q.pop();
            int i=top/n;
            int j=top%n;
            fill(i-1,j,board);
            fill(i+1,j,board);
            fill(i,j-1,board);
            fill(i,j+1,board);
        }
    }
    void solve(vector<vector<char>> &board)

   {
        n=board.size();
        if(n<=2)return;
        for(int i=0;i<n;i++)
        {
            BFS(i,0,board);
            BFS(i,n-1,board);
        }
        for(int j=1;j<n-1;j++)
        {
            BFS(0,j,board);
            BFS(n-1,j,board);
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(board[i][j]=='O')board[i][j]='X';
                else if(board[i][j]=='D')board[i][j]='O';
            }
        }
    }