对并查集还不怎么了解的朋友可以点击这里观看并查集算法的细致讲解
LeetCode-547 省份数量(连通分量计数问题)
题目描述
有 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
提示
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] 为 1 或 0
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
分析
本题考察的是并查集的连通分量计数问题。
我们将每一座城市看作是连通分量,只有在合并两座城市的时候,总的连通分量个数就会减一。
更形象地来说,好比玻璃上有3滴水珠,当两滴水珠融合时,玻璃上就只有3-1滴水珠了。
那么我们应当定义一个初始量为numOfSets
,意为集合的个数。
每次进行合并操作时,只要不是同一个省份的城市就将numOfSets--;
如何知道这两个城市不是同一个省份的呢?只要看两个城市的祖先是不是同一个就行了
题解
class Solution {
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isConnected[i][j] == 1) {
unionFind.union(i, j);
}
}
}
return unionFind.getNumsOfSets();
}
class UnionFind {
private final int[] arr;
private Integer numsOfSets;
public UnionFind(int size) {
numsOfSets = size;
arr = new int[size];
for (int i = 0; i < size; ++i) {
arr[i] = i;
}
}
// 查找并压缩路径
public int find(int son) {
int father = son;
while (arr[father] != father) {
father = arr[father];
}
int next = son;
while (arr[next] != father) {
next = arr[son];
arr[son] = father;
}
return father;
}
// 合并
public void union(int son1, int son2) {
int father1 = find(son1);
int father2 = find(son2);
if(father1 != father2) {
arr[find(son1)] = find(son2);
numsOfSets--; // 集合数-1
}
}
public int getNumsOfSets() {
return numsOfSets;
}
}
}
看似代码一大串,实际上除了并查集模板和两个循环,剩下留给自己发挥的余地所剩无几了。
所以并查集的简单好用实在是让人不得不服。
未完待续... ...