Number of connected components of a graph ( using Disjoint Set Union )
Last Updated :
19 Apr, 2024
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Stores the parent of each vertex
int parent[1000000];
// Function to find the topmost
// parent of vertex a
int root(int a)
{
// If current vertex is
// the topmost vertex
if (a == parent[a]) {
return a;
}
// Otherwise, set topmost vertex of
// its parent as its topmost vertex
return parent[a] = root(parent[a]);
}
// Function to connect the component
// having vertex a with the component
// having vertex b
void connect(int a, int b)
{
// Connect edges
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
// Function to find unique top most parents
void connectedComponents(int n)
{
set<int> s;
// Traverse all vertices
for (int i = 0; i < n; i++) {
// Insert all topmost
// vertices obtained
s.insert(root(parent[i]));
}
// Print count of connected components
cout << s.size() << '\n';
}
// Function to print answer
void printAnswer(int N,
vector<vector<int> > edges)
{
// Setting parent to itself
for (int i = 0; i <= N; i++) {
parent[i] = i;
}
// Traverse all edges
for (int i = 0; i < edges.size(); i++) {
connect(edges[i][0], edges[i][1]);
}
// Print answer
connectedComponents(N);
}
// Driver Code
int main()
{
// Given N
int N = 8;
// Given edges
vector<vector<int> > edges = {
{ 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 }
};
// Function call
printAnswer(N, edges);
return 0;
}
Java
import java.util.*;
class GFG {
// Stores the parent of each vertex
static int[] parent = new int[1000000];
// Function to find the topmost parent of vertex a
static int root(int a) {
if (a == parent[a]) {
return a;
}
return parent[a] = root(parent[a]);
}
// Function to connect the component having vertex a with the component having vertex b
static void connect(int a, int b) {
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
// Function to find unique top most parents
static void connectedComponents(int n) {
HashSet<Integer> s = new HashSet<Integer>();
// Traverse all vertices
for (int i = 0; i < n; i++) {
// Insert all topmost vertices obtained
s.add(root(i));
}
// Print count of connected components
System.out.println(s.size());
}
// Function to print answer
static void printAnswer(int N, int[][] edges) {
// Setting parent to itself
for (int i = 0; i <= N; i++) {
parent[i] = i;
}
// Traverse all edges
for (int i = 0; i < edges.length; i++) {
connect(edges[i][0], edges[i][1]);
}
// Print answer
connectedComponents(N);
}
// Driver Code
public static void main(String[] args) {
// Given N
int N = 8;
// Given edges
int[][] edges = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 4, 5 }, { 4, 6 }, { 4, 0 } };
// Function call
printAnswer(N, edges);
}
}
Python3
# Python3 program for the above approach
from collections import defaultdict
# Given N
N = 8
# Given edges
edges = [[1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]]
# Stores the parent of each vertex
parent = list(range(N))
# Function to find the topmost
# parent of vertex x
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()))
# This code is contributed by Shivam Dwivedi
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Stores the parent of each vertex
static int[] parent = new int[1000000];
// Function to find the topmost
// parent of vertex a
static int root(int a)
{
// If current vertex is
// the topmost vertex
if (a == parent[a]) {
return a;
}
// Otherwise, set topmost vertex of
// its parent as its topmost vertex
return parent[a] = root(parent[a]);
}
// Function to connect the component
// having vertex a with the component
// having vertex b
static void connect(int a, int b)
{
// Connect edges
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
// Function to find unique top most parents
static void connectedComponents(int n)
{
HashSet<int> s = new HashSet<int>();
// Traverse all vertices
for (int i = 0; i < n; i++) {
// Insert all topmost
// vertices obtained
s.Add(parent[i]);
}
// Print count of connected components
Console.WriteLine(s.Count);
}
// Function to print answer
static void printAnswer(int N, List<List<int> > edges)
{
// Setting parent to itself
for (int i = 0; i <= N; i++) {
parent[i] = i;
}
// Traverse all edges
for (int i = 0; i < edges.Count; i++) {
connect(edges[i][0], edges[i][1]);
}
// Print answer
connectedComponents(N);
}
// Driver code
static void Main() {
// Given N
int N = 8;
// Given edges
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 });
// Function call
printAnswer(N, edges);
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Javascript program for the above approach
// Stores the parent of each vertex
var parent = Array(1000000);
// Function to find the topmost
// parent of vertex a
function root(a)
{
// If current vertex is
// the topmost vertex
if (a == parent[a]) {
return a;
}
// Otherwise, set topmost vertex of
// its parent as its topmost vertex
return parent[a] = root(parent[a]);
}
// Function to connect the component
// having vertex a with the component
// having vertex b
function connect( a, b)
{
// Connect edges
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
// Function to find unique top most parents
function connectedComponents( n)
{
var s = new Set();
// Traverse all vertices
for (var i = 0; i < n; i++) {
// Insert all topmost
// vertices obtained
s.add(parent[i]);
}
// Print count of connected components
document.write( s.size + "<br>");
}
// Function to print answer
function printAnswer( N, edges)
{
// Setting parent to itself
for (var i = 0; i <= N; i++) {
parent[i] = i;
}
// Traverse all edges
for (var i = 0; i < edges.length; i++) {
connect(edges[i][0], edges[i][1]);
}
// Print answer
connectedComponents(N);
}
// Driver Code
// Given N
var N = 8;
// Given edges
var edges = [
[ 1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]
];
// Function call
printAnswer(N, edges);
</script>
Time Complexity: O(NLOGN+M)
Auxiliary Space: O(N+M)
Similar Reads
Count of unique lengths of connected components for an undirected graph using STL Given an undirected graph, the task is to find the size of each connected component and print the number of unique sizes of connected components As depicted above, the count(size of the connected component) associated with the connected components is 2, 3, and 2. Now, the unique count of the compone
10 min read
Queries to find number of connected grid components of given sizes in a Matrix Given a matrix mat[][] containing only of 0s and 1s, and an array queries[], the task is for each query, say k, is to find the number of connected grid components (cells consisting of 1s) of size k. Note: Two cells are connected if they share an edge in the direction up, down, left, and right not di
14 min read
Sum of the minimum elements in all connected components of an undirected graph Given an array A of N numbers where A i represent the value of the (i+1) th node. Also given are M pair of edges where u and v represent the nodes that are connected by an edge. The task is to find the sum of the minimum element in all the connected components of the given undirected graph. If a nod
7 min read
Number of ways to select a node from each connected component Given a graph with N nodes and M edges. The task is to find the number of ways to select a node from each connected component of the given graph.Examples: Input: Output: 3 (1, 4), (2, 4), (3, 4) are possible ways.Input: Output: 6 (1, 4, 5), (2, 4, 5), (3, 4, 5), (1, 4, 6), (2, 4, 6), (3, 4, 6) are p
6 min read
Find Weakly Connected Components in a Directed Graph Weakly Connected Graph: A directed graph 'G = (V, E)' is weakly connected if the underlying undirected graph Ä is connected. The underlying undirected graph is the graph Ä = (V, Ã) where à represents the set of undirected edges that is obtained by removing the arrowheads from the directed edges and
9 min read
Octal equivalents of connected components in Binary valued graph Given a binary valued undirected graph with V vertices and E edges, the task is to find the octal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: Chain
15+ min read