并查集是一种用于处理集合合并及查询问题的数据结构
它主要支持两种操作:合并(Union)和查找(Find)
基本思想:将每个元素看作一个节点,每个节点都有一个父节点,如果两个节点的父节点相同,则它们属于同一个集合。初始时,每个节点的父节点都是它自己,表示每个节点都是一个独立的集合。当两个节点需要合并时,只需要将其中一个节点的父节点指向另一个节点的父节点即可。并查集的查找操作是通过递归查找父节点来实现的。
应用:在图论中用于判断两个节点是否连通,以及在最小生成树算法中用于判断是否形成环等
并查集的时间复杂度主要取决于集合的深度,因此在实际应用中需要注意尽量避免出现深度过大的情况,可以通过路径压缩等优化方式来减小集合的深度。
并查集:
根据集合深度合并:
1 | public class UnionFind { |
根据集合大小合并:
1 | /** |
应用:
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份:是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
示例 1:
输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
输出:2
示例 2:
输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
输出:3
来源:力扣(LeetCode)547题
链接:https://leetcode.cn/problems/number-of-provinces
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57class Solution {
public int findCircleNum(int[][] isConnected) {
UnionFind unionFind = new UnionFind(isConnected.length);
for (int i = 0; i < isConnected.length; i++) {
for (int j = i + 1; j < isConnected.length; j++) {
if (isConnected[i][j] == 1) {
unionFind.union(i, j);
}
}
}
return unionFind.getCount();
}
}
class UnionFind{
private int[] parent;
private int[] rank;
private int count;
public UnionFind(int n){
parent=new int[n];
rank=new int[n];
count=n;
for (int i = 0; i < n; i++) {
parent[i]=i;
rank[i]=1;
}
}
public int find(int x){
if (parent[x]!=x){
parent[x]=find(parent[x]);
}
return parent[x];
}
public void union(int x,int y){
int rootX = find(x);
int rootY = find(y);
if (rootX==rootY){
return;
}
if (rank[rootX]>rank[rootY]){
parent[rootY]=rootX;
}else if(rank[rootX] < rank[rootY]){
parent[rootX]=rootY;
}else{
parent[rootY]=rootX;
rank[rootX]++;
}
count--;
}
public int getCount() {
return count;
}
}
- 本文作者: zzr
- 本文链接: http://zzruei.github.io/2023/03fcff9e09.html
- 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!