323. Number of Connected Components in an Undirected Graph
class Solution {
// union-find
int count;
int[] graph;
int[] size;
public int countComponents(int n, int[][] edges) {
// initialize the array representation of graph;
graph = new int[n];
size = new int[n];
for(int i = 0; i<graph.length; i++){
graph[i] = i;
size[i] = 1;
}
count = n;
for(int[] edge : edges){
union(edge[0], edge[1]);
}
return count;
}
private void union(int p, int q){
int rootP = find(p);
int rootQ = find(q);
if(rootP!=rootQ){
if(size[rootP]>size[rootQ]){
graph[rootQ] = rootP;
}else{
graph[rootP] = rootQ;
}
int sum = size[rootP]+size[rootQ];
size[rootQ]=sum;
size[rootQ]=sum;
count--;
}
}
// find the root of vertex i
private int find(int i){
while(graph[i]!=i){
// remember: reduce time complexity
graph[i]=graph[graph[i]];
i=graph[i];
}
return i;
}
}Last updated
Was this helpful?