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 components is 2 and 3. Hence, the expected result is Count = 2
Examples:
Input: N = 7
Output: 1 2 Count = 2
3 4 5 Count = 3
6 7 Count = 2
Unique Counts of connected components: 2
Input: N = 10
Output: 1 Count = 1
2 3 4 5 Count = 4
6 7 8 Count = 3
9 10 Count = 2
Unique Counts of connected components: 4
Prerequisites: Depth First Search
Approach:
The basic idea is to utilize the Depth First Search traversal method to keep a track of the connected components in the undirected graph. An STL container Set is used to store the unique counts of all such components since it is known that a set has the property of storing unique elements in a sorted manner. Finally, extracting the size of the Set gives us the necessary result. The step-wise implementation is as follows:
- Initialize a hash container (Set), to store the unique counts of connected components.
- Recursively call Depth First Search traversal.
- For every vertex visited, store the count in the set container.
- The final size of the Set is the required result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void add_edge( int u, int v, vector< int > graph[])
{
graph[u].push_back(v);
graph[v].push_back(u);
}
void depthFirst( int v, vector< int > graph[],
vector< bool >& visited, int & ans)
{
visited[v] = true ;
cout << v << " " ;
ans++;
for ( auto i : graph[v]) {
if (visited[i] == false ) {
depthFirst(i, graph, visited, ans);
}
}
}
void UniqueConnectedComponent( int n,
vector< int > graph[])
{
vector< bool > visited(n + 1, false );
unordered_set< int > result;
for ( int i = 1; i <= n; i++) {
if (visited[i] == false ) {
int ans = 0;
depthFirst(i, graph, visited, ans);
result.insert(ans);
cout << "Count = " << ans << "\n" ;
}
}
cout << "Unique Counts of "
<< "connected components: " ;
cout << result.size() << "\n" ;
}
int main()
{
int n = 7;
vector< int > graph[n + 1];
add_edge(1, 2, graph);
add_edge(3, 4, graph);
add_edge(3, 5, graph);
add_edge(6, 7, graph);
UniqueConnectedComponent(n, graph);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void add_edge( int u, int v,
Vector<Integer> graph[])
{
graph[u].add(v);
graph[v].add(u);
}
static int depthFirst( int v,
Vector<Integer> graph[],
Vector<Boolean> visited,
int ans)
{
visited.set(v, true );
System.out.print(v + " " );
ans++;
for ( int i : graph[v])
{
if (visited.get(i) == false )
{
ans = depthFirst(i, graph, visited, ans);
}
}
return ans;
}
static void UniqueConnectedComponent( int n,
Vector<Integer> graph[])
{
Vector<Boolean> visited = new Vector<>();
for ( int i = 0 ; i < n + 1 ; i++)
visited.add( false );
HashSet<Integer> result = new HashSet<>();
for ( int i = 1 ; i <= n; i++)
{
if (visited.get(i) == false )
{
int ans = 0 ;
ans = depthFirst(i, graph, visited, ans);
result.add(ans);
System.out.print( "Count = " +
ans + "\n" );
}
}
System.out.print( "Unique Counts of " +
"connected components: " );
System.out.print(result.size() + "\n" );
}
public static void main(String[] args)
{
int n = 7 ;
@SuppressWarnings ( "unchecked" )
Vector<Integer>[] graph = new Vector[n+ 1 ];
for ( int i = 0 ; i < graph.length; i++)
graph[i] = new Vector<Integer>();
add_edge( 1 , 2 , graph);
add_edge( 3 , 4 , graph);
add_edge( 3 , 5 , graph);
add_edge( 6 , 7 , graph);
UniqueConnectedComponent(n, graph);
}
}
|
Python3
graph = [[] for i in range ( 100 + 1 )]
visited = [ False ] * ( 100 + 1 )
ans = 0
def add_edge(u, v):
graph[u].append(v)
graph[v].append(u)
def depthFirst(v):
global ans
visited[v] = True
print (v, end = " " )
ans + = 1
for i in graph[v]:
if (visited[i] = = False ):
depthFirst(i)
def UniqueConnectedComponent(n):
global ans
result = {}
for i in range ( 1 , n + 1 ):
if (visited[i] = = False ):
depthFirst(i)
result[ans] = 1
print ( "Count = " , ans)
ans = 0
print ( "Unique Counts of connected "
"components: " , end = "")
print ( len (result))
if __name__ = = '__main__' :
n = 7
add_edge( 1 , 2 )
add_edge( 3 , 4 )
add_edge( 3 , 5 )
add_edge( 6 , 7 )
UniqueConnectedComponent(n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void add_edge( int u, int v,
List< int > []graph)
{
graph[u].Add(v);
graph[v].Add(u);
}
static int depthFirst( int v,
List< int > []graph,
List<Boolean> visited,
int ans)
{
visited.Insert(v, true );
Console.Write(v + " " );
ans++;
foreach ( int i in graph[v])
{
if (visited[i] == false )
{
ans = depthFirst(i, graph,
visited, ans);
}
}
return ans;
}
static void UniqueConnectedComponent( int n,
List< int > []graph)
{
List<Boolean> visited = new List<Boolean>();
for ( int i = 0; i < n + 1; i++)
visited.Add( false );
HashSet< int > result = new HashSet< int >();
for ( int i = 1; i <= n; i++)
{
if (visited[i] == false )
{
int ans = 0;
ans = depthFirst(i, graph, visited, ans);
result.Add(ans);
Console.Write( "Count = " +
ans + "\n" );
}
}
Console.Write( "Unique Counts of " +
"connected components: " );
Console.Write(result.Count + "\n" );
}
public static void Main(String[] args)
{
int n = 7;
List< int > []graph = new List< int >[n + 1];
for ( int i = 0; i < graph.Length; i++)
graph[i] = new List< int >();
add_edge(1, 2, graph);
add_edge(3, 4, graph);
add_edge(3, 5, graph);
add_edge(6, 7, graph);
UniqueConnectedComponent(n, graph);
}
}
|
Javascript
<script>
function add_edge(u,v,graph)
{
graph[u].push(v);
graph[v].push(u);
}
function depthFirst(v, graph,visited,ans)
{
visited[v] = true ;
document.write(v + " " );
ans++;
for (let i=0;i< graph[v].length;i++)
{
if (visited[graph[v][i]] == false )
{
ans = depthFirst(graph[v][i], graph, visited, ans);
}
}
return ans;
}
function UniqueConnectedComponent(n,graph)
{
let visited = [];
for (let i = 0; i < n + 1; i++)
visited.push( false );
let result = new Set();
for (let i = 1; i <= n; i++)
{
if (visited[i] == false )
{
let ans = 0;
ans = depthFirst(i, graph, visited, ans);
result.add(ans);
document.write( "Count = " +
ans + "<br>" );
}
}
document.write( "Unique Counts of " +
"connected components: " );
document.write(result.size + "<br>" );
}
let n = 7;
let graph = new Array(n + 1);
for (let i = 0; i < graph.length; i++)
graph[i] = [];
add_edge(1, 2, graph);
add_edge(3, 4, graph);
add_edge(3, 5, graph);
add_edge(6, 7, graph);
UniqueConnectedComponent(n, graph);
</script>
|
Output:
1 2 Count = 2
3 4 5 Count = 3
6 7 Count = 2
Unique Counts of connected components: 2
Time Complexity:
As evident from the above implementation, the graph is traversed using the Depth First Search algorithm. The individual counts are stored using Set container wherein the insertion operation takes O(1) time. The overall complexity is solely based on the time taken by the DFS algorithm to run recursively. Hence, the time complexity of the program is O(E + V) where E is the number of edges and V is the number of vertices of the graph.
Auxiliary Space: O(N)
Last Updated :
30 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...