Number of Connected Components in an Undirected Graph
Description
null
Solution(javascript)
/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countComponents = function(n, edges) {
const parent = new Array(n).fill(0).map((x, index) => index)
const root = (a) => {
while(a !== parent[a]) {
parent[a] = parent[parent[a]]
a = parent[a]
}
return a
}
let size = n
const union = (a, b) => {
const rootA = root(a)
const rootB = root(b)
if(rootA !== rootB) {
size -= 1
parent[rootA] = rootB
}
}
edges.forEach(([a, b]) => {
union(a,b)
})
return size
};