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;
}
}
class Solution {
boolean[] visited;
int count;
public int countComponents(int n, int[][] edges) {
visited = new boolean[n];
List<Integer>[] graph = buildGraph(edges, n);
for(int i=0; i<graph.length; i++){
if(!visited[i]){
count++;
traverse(graph, i);
}
}
return count;
}
private void traverse(List<Integer>[] graph, int curr){
visited[curr]=true;
for(int next: graph[curr]){
if(!visited[next]){
traverse(graph, next);
}
}
}
private List<Integer>[] buildGraph(int[][] edges, int n){
List<Integer>[] graph = new LinkedList[n];
for(int i = 0; i<graph.length; i++){
graph[i] = new LinkedList<>();
}
for(int i=0; i<edges.length; i++){
int from = edges[i][0];
int to = edges[i][1];
// undirected graph;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
}
Last updated
Was this helpful?