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'.spa

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';
            }
        }
    }
};
相關文章
相關標籤/搜索