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

思路:这题一拿到收,我们就可以知道用搜索来解题,至于如何如何是关键。我们从外围'O'开始往深度走,如果内部的'O'和外围的'O'是连通的,那么这些'O'可以存活,反之,就被'X'吃掉。为了区分这两种情况,我们使用'#'做区分,为了后期恢复存货的'O'.

class Solution {

public:

    void DFS(int x,int y,vector<vector<char> > &board)

    {

        if(x>=0&&x<board.size()&&y>=0&&y<board[0].size()&&board[x][y]=='O')

        {

            board[x][y]='#';

            DFS(x-1,y,board);

            DFS(x+1,y,board);

            DFS(x,y-1,board);

            DFS(x,y+1,board);

        }

    }

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

        if(board.empty()||board.size()==0||board[0].size()==0)

            return;

        int m=board.size();

        int n=board[0].size();

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

        {

            DFS(0,i,board);

            DFS(m-1,i,board);

        }

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

        {

            DFS(i,0,board);

            DFS(i,n-1,board);

        }

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

        {

            for(int j=0;j<n;j++)

            {

                board[i][j]=board[i][j]=='#'?'O':'X';

            }

        }

    }

};

 

你可能感兴趣的:(round)