其他分享
首页 > 其他分享> > LeetCode 130 Surrounded Regions 连通块DFS

LeetCode 130 Surrounded Regions 连通块DFS

作者:互联网

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Solution

如果由 'O' 组成的一个连通块没有与边界相连, 那么最后就会被翻转成 'X'。因此我们可以从边界出发进行 \(DFS\):此时得到的连通块都是不会被翻转的,我们用 '#' 标记即可。最后统计时,没有被 '#' 标记的 'O' 都是被翻转的。

点击查看代码
class Solution {
private:
    int dx[4][2]={
        1,0,
        0,1,
        -1,0,
        0,-1
    };
    bool check(int i,int j,int n,int m){
        if(i<0 || j<0 || i>=n || j>=m) return false;
        return true;
    }
    void dfs(vector<vector<char>>& board, int x, int y, int n, int m){
        for(int i=0;i<4;i++){
            int nx = x+dx[i][0], ny = y+dx[i][1];
            if(check(nx,ny,n,m)){
                if(board[nx][ny]=='O'){
                    board[nx][ny]='#';dfs(board,nx,ny,n,m);
                }
            }
        }
    }
    
public:
    void solve(vector<vector<char>>& board) {
        int n = board.size(), m = board[0].size();
        if(n==0)return;
        for(int i=0;i<n;i++){
            if(board[i][0]=='O'){board[i][0]='#';dfs(board,i,0,n,m);}
            if(board[i][m-1]=='O'){board[i][m-1]='#';dfs(board,i,m-1,n,m);}
        }
        for(int j=0;j<m;j++){
            if(board[0][j]=='O'){board[0][j]='#';dfs(board,0,j,n,m);}
            if(board[n-1][j]=='O'){board[n-1][j]='#';dfs(board,n-1,j,n,m);}
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(board[i][j]=='#')board[i][j]='O';
                else if(board[i][j]=='O')board[i][j]='X';
            }
        }
    }
};

标签:连通,return,int,Surrounded,DFS,Regions,board,size,翻转
来源: https://www.cnblogs.com/xinyu04/p/16278476.html