Java 并查集解决 leetcode200岛屿问题 思路

//伪代码
//并查集
UnionFind(grid): //并查集构造函数
    row = len(grid)
    col = len(grid[0])
    count = row * col                //总数
    root = [-1]*(row*col)           // 二维数组→一维数组
    for i in [0, len(root)]:       //初始化
        root[i] = i;           

int find(x):           //返回x的祖先
    if x == root[x]:
        return x
    else:
        root[x] = find(root[x])
        return root[x]

void Union(x,y):         //合并x,y为同一祖先
    rootX = find(x);
    rootY = find(y);
    if rootX != rootY:   // 祖先不相等 把x的祖先的值变成y的祖先
        root[rootX] = rootY
        count--           //减去同化的数量

int getCount():

//并查集求小岛问题
int func(grid):    
    if grid == null or len(grid) == 0
        return 0
    row = len(grid)
    col = len(grid[0])
    waters = 0
    of = UnionFind(grid)          //输入并查集
    for i in [0,row]:
        for j in [0,col]:
          if grid[i][j] == 0     //水域
            waters++
          else:
            directions = [[0,1],[0,-1],[1,0],[-1,0]] //陆地 四周同化祖先
            for d in directions:
                x = i + d[0];
                y = j + d[1];
                //周围合法且为1
                if x >= 0 and x < row and y >=0 and y < col and grid[x][y] == '1': 
                    of.union( x*col+y, i*col+y)    //同化祖先 x*col+y:二维变一维
return of.getCount() - waters; //总数-同化-水 = 岛

你可能感兴趣的:(java,算法,java,开发语言,后端)