什么是并查集
有多个集合,集合内有多个元素
并查集算法用来查找一个元素所属的集合,合并两个元素各自所属的集合。称为并查集
算法举例
亲戚关系的等价问题,犯罪团伙的头目。
给出很多人的亲戚相互间关系,查找任意两人是否为亲戚。
多个犯罪分子各自在自己的团伙中,找到犯罪团伙的数量。
算法思路
使用树的数据结构来实现并查集算法。
关键点:
- 初始化集合,刚开始每个元素为一个集合,该元素就代表了该集合;如果有多个元素,根元素代表一个集合。根节点的parent指针指向自己。(元素间虽然有父子关系但是不意味者有从属关系,只是起到联系集合元素的作用)
- 查找一个元素所属的集合。找该元素所在集合的根节点。
- 合并集合。为了使合并后的树的高度更小,需要将高度较小的树作为高度较大的树的子树。若两树的高度相等需要将高度+1;
算法实现
java实现
public static class UnionFind {
UnionFind[] set = null;
UnionFind parent = this;
int rank = 1;
public UnionFind(int n) {
set = new UnionFind[n];
}
public UnionFind findRoot(UnionFind x) {
if (x.parent == x) {
return x;
}
return findRoot(x.parent);
}
public UnionFind union(UnionFind left, UnionFind right) {
UnionFind rootx = left.findRoot(left);
UnionFind rooty = left.findRoot(right);
if (rootx != rooty) {
if (rootx.rank < rooty.rank) {
rootx.parent = rooty;
return rooty;
} else if (rootx.rank > rooty.rank) {
rooty.parent = rootx;
return rootx;
} else {
rootx.parent = rooty;
rootx.rank++;
return rootx;
}
}
return rootx;
}
}
时间复杂度
主要时间在查找元素所在的集合即找根节点。所有时间复杂度为logN。N为元素个数
应用 leetcode 200题
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
输出:1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
class Solution {
public int numIslands(char[][] grid) {
int rown = grid.length;
int coln = grid[0].length;
UnionFind set = new UnionFind(grid.length * grid[0].length);
for (int i = 0; i < rown; i++) {
for (int j = 0; j < coln; j++) {
if (grid[i][j] == '1') {
System.out.println("初始化"+(i*coln+j));
UnionFind f = new UnionFind(1);
set.set[i * coln + j] = f;
}
}
}
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
for (int i = 0; i < rown; i++) {
for (int j = 0; j < coln; j++) {
if (grid[i][j] == '1') {
for (int k = 0; k < dx.length; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (x >= 0 && y >= 0 && x < rown && y < coln) {
if(grid[x][y]=='1'){
System.out.println("合并"+"i"+i+"j"+j+"x"+x+"y"+y);
set.set[i*coln+j]=set.union(set.set[x*coln+y],set.set[i*coln+j]);
}
}
}
}
}
}
Set<UnionFind> res=new HashSet<>();
for (int i = 0; i < rown * coln; i++) {
if(set.set[i]!=null){
UnionFind root =set.findRoot(set.set[i]);
res.add(root);
}
}
return res.size();
}
public static class UnionFind {
UnionFind[] set = null;
UnionFind parent = this;
int rank = 1;
public UnionFind(int n) {
set = new UnionFind[n];
}
public UnionFind findRoot(UnionFind x) {
if (x.parent == x) {
return x;
}
return findRoot(x.parent);
}
public UnionFind union(UnionFind left, UnionFind right) {
UnionFind rootx = left.findRoot(left);
UnionFind rooty = left.findRoot(right);
if (rootx != rooty) {
if (rootx.rank < rooty.rank) {
rootx.parent = rooty;
return rooty;
} else if (rootx.rank > rooty.rank) {
rooty.parent = rootx;
return rootx;
} else {
rootx.parent = rooty;
rootx.rank++;
return rootx;
}
}
return rootx;
}
}
}