题目描述
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
解题思路
算法
并查集
过程
以城市的数量为 n 作为并查集 fa 的长度
对 isConnected 进行两层 for 遍历,把连接情况更新到并查集
最后对于返回的结果,我们遍历 fa,只要 index 不等于当前 value,说明他的 root 在别处,因此我们让结果 +1
代码
/**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function (isConnected) {
const unionSet = new UnionSet22(isConnected.length)
for (let i = 0; i < isConnected.length; i++) {
const arr = isConnected[i]
for (let j = 0; j < arr.length; j++) {
if (j !== i && arr[j]) {
unionSet.merge(i + 1, j + 1)
}
}
}
return unionSet.fa.reduce((pre, cur, index) => {
if (index === cur) {
return pre + 1
}
return pre
}, -1)
}
class UnionSet22 {
constructor(n) {
this.n = n
this.fa = []
for (let i = 0; i <= n; i++) {
this.fa[i] = i
}
}
get(x) {
return (this.fa[x] = this.fa[x] === x ? x : this.get(this.fa[x]))
}
merge(a, b) {
this.fa[this.get(a)] = this.get(this.fa[b])
}
}