一.并查集的简单介绍
二. 并查集的主要构成和实现方式
三.HashMap模板和数组模板
由于在下文的模板基本一致,不再每次都罗列,大体的模板如下,若有错误可以在leetcode找到对应的题目解答,已经附上连接。
HashMap
class UnionFind {
private Map<Integer,Integer> father;
public UnionFind() {
father = new HashMap<Integer,Integer>();
}
public void add(int x) {
if (!father.containsKey(x)) {
father.put(x, null);
}
}
public void merge(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY){
father.put(rootX,rootY);
}
}
public int find(int x) {
int root = x;
while(father.get(root) != null){
root = father.get(root);
}
while(x != root){
int original_father = father.get(x);
father.put(x,root);
x = original_father;
}
return root;
}
public boolean isConnected(int x, int y) {
return find(x) == find(y);
}
}
数组
class UnionFind{
public int[] parent;
public int count;
//初始化
public UnionFind(int n){
parent = new int[n];
count = n;
for(int i = 0; i< n; i++){
parent[i] = i;
}
}
//查找
public int find(int x){
while(x != parent[x]){
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
//合并节点
public void union(int x, int y){
if(find(x) == find(y)) return;
parent[find(x)] = find(y);
count--;
}
//是否为同一父节点,也就是是否联通
public boolean isConnected(int x, int y){
return find(x) == find(y);
}
//返回数量
public int getCount(){
return count;
}
}
三. leetcode实战
1. leetcode547 省份数量
2. leetcode684 冗余连接
以上未出现部分圈全在在前篇文章,不再赘述
3. leetcode1905 统计子岛屿
给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域