Surrounded Regions - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday 18 August 2020

Surrounded Regions

Surrounded Regions


 Surrounded Regions


Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

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

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

class Solution {

public:

    void solve(vector<vector<char>>& board) {

        queue<pair<int,int>> q;

        if(board.size()==0)return;

            

        int j=0;

        for(int i=0;i<board.size();++i)

        {

            if(board[i][j]=='O')

                {

                q.push({i,j});

                }

        }

    

        j=board[0].size()-1;

        int m=j+1;

        for(int i=0;i<board.size();++i)

        {

                if(board[i][j]=='O')

                {

                q.push({i,j});

                }

        }

    

        int i=0;

        for(int j=0;j<board[0].size();++j)

            {

                if(board[i][j]=='O')

                {

                q.push({i,j});

                }

            }

    

    

         i=board.size()-1;

        int  n=i+1;

        for(int j=0;j<board[0].size();++j)

            {

                if(board[i][j]=='O')

                {

                q.push({i,j});

                }

            }

          vector<pair<int,int> > v{{0,1},{1,0},{-1,0},{0,-1}};

        

        while(!q.empty())

        {

            auto p=q.front();

            q.pop();

            if(board[p.first][p.second]=='I')

                continue;

            

            

            board[p.first][p.second]='I';

                

            for(int i=0;i<4;++i)

            {

                int x=v[i].first+p.first;

                int y=v[i].second+p.second;

                if(x<0||y<0||x>=n||y>=m||board[x][y]=='X')continue;

                q.push({x,y});

            }

        }

        

          for(int i=0;i<board.size();++i)

          {

           for(int j=0;j<board[0].size();++j)

            {

                if(board[i][j]=='O')

                {

                    board[i][j]='X';

                }

                if(board[i][j]=='I')

                {

                    board[i][j]='O';

                }

           }

         }

    

    }

};