Number of connected components of a graph ( using Disjoint Set Union )
Given an undirected graph G with vertices numbered in the range [0, N] and an array Edges[][] consisting of M edges, the task is to find the total number of connected components in the graph using Disjoint Set Union algorithm.
Examples:
Input: N = 4, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}
Output: 2
Explanation: There are only 2 connected components as shown below:
Input: N = 7, Edges[][] = {{1, 0}, {0, 2}, {3, 5}, {3, 4}, {6, 7}}
Output: 3
Explanation: There are only 3 connected components as shown below:
Approach: The problem can be solved using Disjoint Set Union algorithm. Follow the steps below to solve the problem:
- In DSU algorithm, there are two main functions, i.e. connect() and root() function.
- connect(): Connects an edge.
- root(): Recursively determine the topmost parent of a given edge.
- For each edge {a, b}, check if a is connected to b or not. If found to be false, connect them by appending their top parents.
- After completing the above step for every edge, print the total number of the distinct top-most parents for each vertex.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int parent[1000000];
int root( int a)
{
if (a == parent[a]) {
return a;
}
return parent[a] = root(parent[a]);
}
void connect( int a, int b)
{
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
void connectedComponents( int n)
{
set< int > s;
for ( int i = 0; i < n; i++) {
s.insert(root(parent[i]));
}
cout << s.size() << '\n' ;
}
void printAnswer( int N,
vector<vector< int > > edges)
{
for ( int i = 0; i <= N; i++) {
parent[i] = i;
}
for ( int i = 0; i < edges.size(); i++) {
connect(edges[i][0], edges[i][1]);
}
connectedComponents(N);
}
int main()
{
int N = 8;
vector<vector< int > > edges = {
{ 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 }
};
printAnswer(N, edges);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int []parent = new int [ 1000000 ];
static int root( int a)
{
if (a == parent[a])
{
return a;
}
return parent[a] = root(parent[a]);
}
static void connect( int a, int b)
{
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
static void connectedComponents( int n)
{
HashSet<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
{
s.add(parent[i]);
}
System.out.println(s.size());
}
static void printAnswer( int N, int [][] edges)
{
for ( int i = 0 ; i <= N; i++)
{
parent[i] = i;
}
for ( int i = 0 ; i < edges.length; i++)
{
connect(edges[i][ 0 ], edges[i][ 1 ]);
}
connectedComponents(N);
}
public static void main(String[] args)
{
int N = 8 ;
int [][]edges = {{ 1 , 0 }, { 0 , 2 },
{ 5 , 3 }, { 3 , 4 },
{ 6 , 7 }};
printAnswer(N, edges);
}
}
|
Python3
from collections import defaultdict
N = 8
edges = [[ 1 , 0 ], [ 0 , 2 ], [ 5 , 3 ], [ 3 , 4 ], [ 6 , 7 ]]
parent = list ( range (N))
def find(x):
if x ! = parent[x]:
parent[x] = find(parent[x])
return parent[x]
def union(x,y):
parent_x = find(x)
parent_y = find(y)
if parent_x ! = parent_y:
parent[parent_y] = parent_x
for x,y in edges:
union(x,y)
dict_pair = defaultdict( list )
for idx, val in enumerate (parent):
dict_pair[find(val)].append(idx)
print ( len (dict_pair.keys()))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int [] parent = new int [1000000];
static int root( int a)
{
if (a == parent[a]) {
return a;
}
return parent[a] = root(parent[a]);
}
static void connect( int a, int b)
{
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
static void connectedComponents( int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++) {
s.Add(parent[i]);
}
Console.WriteLine(s.Count);
}
static void printAnswer( int N, List<List< int > > edges)
{
for ( int i = 0; i <= N; i++) {
parent[i] = i;
}
for ( int i = 0; i < edges.Count; i++) {
connect(edges[i][0], edges[i][1]);
}
connectedComponents(N);
}
static void Main() {
int N = 8;
List<List< int >> edges = new List<List< int >>();
edges.Add( new List< int > { 1, 0 });
edges.Add( new List< int > { 0, 2 });
edges.Add( new List< int > { 5, 3 });
edges.Add( new List< int > { 3, 4 });
edges.Add( new List< int > { 6, 7 });
printAnswer(N, edges);
}
}
|
Javascript
<script>
var parent = Array(1000000);
function root(a)
{
if (a == parent[a]) {
return a;
}
return parent[a] = root(parent[a]);
}
function connect( a, b)
{
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
function connectedComponents( n)
{
var s = new Set();
for ( var i = 0; i < n; i++) {
s.add(parent[i]);
}
document.write( s.size + "<br>" );
}
function printAnswer( N, edges)
{
for ( var i = 0; i <= N; i++) {
parent[i] = i;
}
for ( var i = 0; i < edges.length; i++) {
connect(edges[i][0], edges[i][1]);
}
connectedComponents(N);
}
var N = 8;
var edges = [
[ 1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]
];
printAnswer(N, edges);
</script>
|
Time Complexity: O(NLOGN+M)
Auxiliary Space: O(N+M)
Last Updated :
28 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...