Surrounded Regions

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
class Solution {
public:
    void solve(vector<vector<char>> &tmp) 
    {
        int m=tmp.size();
        if(m==0) return;
        int n=tmp[0].size();
        //set 1 at edges
        for(int i=0;i<n;i++)
            if(tmp[0][i]=='O') tmp[0][i]=1;
        for(int i=0;i<n;i++)
            if(tmp[m-1][i]=='O') tmp[m-1][i]=1;
        for(int i=0;i<m;i++)
            if(tmp[i][0]=='O') tmp[i][0]=1;
        for(int i=0;i<m;i++)
            if(tmp[i][n-1]=='O') tmp[i][n-1]=1;
        while(true)
        {
            //get a '0' beside 1
            bool find=false;
            int i,j;
            for(i=0;i<m;i++)
            {
                for(j=0;j<n;j++)
                if(tmp[i][j]=='O')
                {
                    if(check(tmp,m,n,i-1,j,1) || check(tmp,m,n,i+1,j,1) ||check(tmp,m,n,i,j-1,1) ||check(tmp,m,n,i,j+1,1))
                    {
                        find=true;
                        break;
                    }
                }
                if(find) break;
            }
            if(!find) break;
            //fill
            while(tmp[i][j]=='O')
            {
                tmp[i][j]=1;
                if(check(tmp,m,n,i-1,j,'O'))
                {
                    i=i-1;continue;
                }
                if(check(tmp,m,n,i+1,j,'O'))
                {
                    i=i+1;continue;
                }
                if(check(tmp,m,n,i,j-1,'O'))
                {
                    j=j-1;continue;
                }
                if(check(tmp,m,n,i,j+1,'O'))
                {
                    j=j+1;continue;
                }
            }
        }
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(tmp[i][j]==1)
                    tmp[i][j]='O';
                else
                    tmp[i][j]='X';
    }
    bool check(const vector<vector<char>> &tmp,int m,int n,int x,int y,char c)
    {
        if(x<0 || x>=m) return false;
        if(y<0 || y>=n) return false;
        if(tmp[x][y]==c) return true;
        return false;
    }
};

 

posted @ 2014-05-30 01:20  erictanghu  阅读(114)  评论(0编辑  收藏  举报