Union Find
并查集是一种高效的数据结构,用于解决 连通问题、成环问题等。
模板
1 | |
547. 省份数量
方法一:BFS
1 | |
方法二:DFS
1 | |
方法三:并查集
1 | |

684. 冗余连接

方法一:并查集
- 初始化为森林,依次连接节点之间的边
- 如果连接边之前,节点不在同一个子集,那么合并
- 如果连接边之前,节点已经在同一个子集了,那么一定会形成环,这条边就是最后的冗余连接
1 | |
1319. 连通网络的操作次数

方法一:并查集
找到连通分量
1
2
3for (int i = 0 ; i < n ; i++)
if (parent[i] == i)
require++;
1 | |
面试题 16.19. 水域大小

方法一:DFS
1 | |
方法二:并查集
使用哈希表count记录池塘的大小
初始化,额外将count赋值1
1
2
3
4
5
6private void init(int n) {
parent = new int[n];
for (int i = 0; i < n; ++i) {
parent[i] = i;
count.put(i, 1);
}如果land[i][j] != 0,那么必然不会是池塘,将count值赋-1
1
2if (land[i][j] != 0)
count.put(i * n + j, -1);遍历依次合并,合并时将新parent的count加上被合并的count,并将被合并的parent的count赋值-1(便于收集结果)
1
2
3
4
5
6
7
8
9
10private boolean union(int i, int j) {
int rootI = findParent(i), rootJ = findParent(j);
if (rootI != rootJ) {
parent[rootI] = rootJ;
count.put(rootJ, count.get(rootI) + count.get(rootJ));
count.put(rootI, -1);
return true;
}
return false;
}收集结果
1
2
3for (int val : count.values())
if (val != -1)
list.add(val);
1 | |

方法一:并查集
1 | |
方法一:并查集

1 | |
Union Find
https://leopol1d.github.io/2023/05/29/union-find/