130. Surrounded Regions(Leetcode每日一题-2020.08.11)

Problem

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

130. Surrounded Regions(Leetcode每日一题-2020.08.11)_第1张图片

Solution

从边缘的O开始,进行DFS,找到所有相连的O。然后将所有没有跟边缘的O相连的O标记成X。

class Solution {
public:
    vector<pair<int,int>> dirs={{-1,0},{1,0},{0,-1},{0,1}};
    void solve(vector<vector<char>>& board) {
        if(board.empty())
            return;
        int m = board.size();
        int n = board[0].size();

        set<pair<int,int>> o_set;
        for(int j = 0;j<n;++j)
        {
            if(board[0][j] == 'O' && !o_set.count({0,j}))//寻找第一行的O
            {
                //插入O集合,并从它开始进行dfs,寻找相连的O
                o_set.insert({0,j});
                dfs({0,j},o_set,board,m,n);
            }

            if(board[m-1][j] == 'O' && !o_set.count({m-1,j}))//寻找最后一行的O
            {
                //插入O集合,并从它开始进行dfs,寻找相连的O
                o_set.insert({m-1,j});
                dfs({m-1,j},o_set,board,m,n);
            }
        }

        for(int i = 1;i<m-1;++i)
        {
            if(board[i][0] == 'O' && !o_set.count({i,0})) //寻找第一列的O
            {
                //插入O集合,并从它开始进行dfs,寻找相连的O
                o_set.insert({i,0});
                dfs({i,0},o_set,board,m,n);
            }

            if(board[i][n-1] == 'O' && !o_set.count({i,n-1}))//寻找最后一列的O
            {
                //插入O集合,并从它开始进行dfs,寻找相连的O
                o_set.insert({i,n-1});
                dfs({i,n-1},o_set,board,m,n);
            }
        }

        //将不在O集合中的O标记成X
        for(int i = 0;i<m;++i)
        {
            for(int j = 0;j<n;++j)
            {
                if(board[i][j] == 'O' && !o_set.count({i,j}))
                    board[i][j] = 'X';
            }
        }
    }

    void dfs(pair<int,int> start,set<pair<int,int>> &o_set,vector<vector<char>>& board,int m,int n)
    {
        for(auto& dir:dirs)
        {
            int x = start.first + dir.first;
            int y = start.second + dir.second;
            if(x >= 0 && x <m && y >=0 && y < n && board[x][y] =='O' && !o_set.count({x,y}))
            {
                o_set.insert({x,y});
                dfs({x,y},o_set,board,m,n);
            }
        }
    }
};

你可能感兴趣的:(letcode深度优先搜索)