LeetCode-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

不被X包住的情况需要一个在边界上的O,从边界上的O开始DFS即可

class Solution {
public:
    void DFS(vector<vector<char> > &board,int i,int j){
        board[i][j]='.';
        if(i>0&&board[i-1][j]=='O')DFS(board,i-1,j);
        if(i<board.size()-1&&board[i+1][j]=='O')DFS(board,i+1,j);
        if(j>0&&board[i][j-1]=='O')DFS(board,i,j-1);
        if(j<board[0].size()-1&&board[i][j+1]=='O')DFS(board,i,j+1);
    }
    void solve(vector<vector<char>> &board) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(board.size()==0||board[0].size()==0)return;
        //set four boundaries
        int m=board[0].size();
        int n=board.size();
        for(int i=0;i<m;i++)if(board[0][i]=='O')DFS(board,0,i);
        for(int i=0;i<m;i++)if(board[n-1][i]=='O')DFS(board,n-1,i);
        for(int i=0;i<n;i++)if(board[i][0]=='O')DFS(board,i,0);
        for(int i=0;i<n;i++)if(board[i][m-1]=='O')DFS(board,i,m-1);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++){
            if(board[i][j]=='O')board[i][j]='X';
            else if(board[i][j]=='.')board[i][j]='O';
        }
    }
};
View Code

 

posted @ 2013-10-08 15:08  懒猫欣  阅读(188)  评论(0编辑  收藏  举报