LeetCode 130 Surrounded Regions(并查集)

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.

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'和'X'二维字符数组,把所有被'X'包围的'O'替换为'X'。

解题思路:把所有不被'X'包围的'O'放在同一个集合里,然后遍历数组,将不在集合中的'O'转换为'X'。

代码如下:

#define MAXN 100005
typedef struct DisjointSet{
    int par,rank;
}DS;
DS ds[MAXN];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

void init(int n)
{
    for(int i = 0;i <= n;i++){
        ds[i].par = i;
        ds[i].rank = 0;
    }
}

int find(int x)
{
    if(x == ds[x].par)
        return x;
    else return ds[x].par = find(ds[x].par);
}

void unite(int x, int y)
{
    x = find(x);
    y = find(y);
    if(x == y) return ;
    if(ds[x].rank < ds[y].rank)
        ds[x].par = y;
    else {
        if(ds[x].rank == ds[y].rank)
            ds[x].rank++;
        ds[y].par = x;
    }
    return ;
}

int same(int x, int y)
{
    return find(x) == find(y);
}

void solve(char** board, int boardRowSize, int boardColSize) {
    int brs = boardRowSize;
    int bcs = boardColSize;
    init(bcs * brs);
    for(int i = 0;i < brs;i++){
        for(int j = 0;j < bcs;j++){
            if((i == 0 || i == brs-1 || j == 0 || j == bcs-1) && board[i][j] == 'O')
                unite(i*brs+j, brs*bcs);
            else if(board[i][j] == 'O'){
                for(int k = 0;k < 4;k++){
                    int x = i + dir[k][0];
                    int y = j + dir[k][1];
                    if(board[x][y] == 'O')
                        unite(i*brs+j, x*brs+y);
                }
            }
        }
    }
    for(int i = 0;i < brs;i++){
        for(int j = 0;j < bcs;j++){
            if(!same(i*brs+j, brs*bcs)) board[i][j] = 'X';
        }
    }
    return ;
}

你可能感兴趣的:(数据结构)