How to Find Connected Components in Graph

In this article, we are going to find connected components in a graph by building a program in C++ language. We are going to use different approaches to build the program for finding the connected components in the graph. We are also going to calculate the time complexity and the space complexity for the program.

Approach 1: Using Depth First Search (DFS)

An undirected graph's connected component search is simpler. In order to obtain all strongly connected components, the concept is to perform DFS starting from each unexplored vertices.

To put the concept into practice using DFS, we should follow the below mentioned steps:

  • Set each vertex's initial state to unvisited.
  • Follow these steps for each vertex v.
  • Call the DFS and print the newline character to print each component in a new line if v has never been visited before.
  • Print out v and mark it as visited.
  • If a neighboring u of v is not visited, recursively call the DFS for that u.

Example 1:

// C++ program to print connected components in
// an undirected graph
#include
using namespace std;
// Graph class represents a undirected graph
// using adjacency list representation
class Graph {
	int V; // No. of vertices


	// Pointer to an array containing adjacency lists
	list* adj;


	// A function used by DFS
	void DFSUtil(int v, bool visited[]);


public:
	Graph(int V); // Constructor
	~Graph();
	void addEdge(int v, int w);
	void connectedComponents();
};


// Method to print connected components in an
// undirected graph
void Graph::connectedComponents()
{
	// Mark all the vertices as not visited
	bool* visited = new bool[V];
	for (int v = 0; v < V; v++)
		visited[v] = false;


	for (int v = 0; v < V; v++) {
		if (visited[v] == false) {
			// print all reachable vertices
			// from v
			DFSUtil(v, visited);


			cout << "\n";
		}
	}
	delete[] visited;
}


void Graph::DFSUtil(int v, bool visited[])
{
	// Mark the current node as visited and print it
	visited[v] = true;
	cout << v << " ";


	// Recur for all the vertices
	// adjacent to this vertex
	list::iterator i;
	for (i = adj[v].begin(); i != adj[v].end(); ++i)
		if (!visited[*i])
			DFSUtil(*i, visited);
}


Graph::Graph(int V)
{
	this->V = V;
	adj = new list[V];
}


Graph::~Graph() { delete[] adj; }


// method to add an undirected edge
void Graph::addEdge(int v, int w)
{
	adj[v].push_back(w);
	adj[w].push_back(v);
}


// Driver code
int main()
{
	// Create a graph given in the above diagram
	Graph g(5); // 5 vertices numbered from 0 to 4
	g.addEdge(1, 0);
	g.addEdge(2, 1);
	g.addEdge(3, 4);


	cout << "Following are connected components \n";
	g.connectedComponents();


	return 0;
}

Output:

Following are connected components
0 1 2
3 4

Time complexity for the following program is - O(V+E).

Space complexity for the following program is - O(V).

Approach 2: Using Disjoint Set Union

In this approach, we first declare each node as a separate subset before visiting each one in order to tackle the problem using DSU (Disjoint Set Union). Join the under with any newly discovered unexplored nodes. In this way, each traversal will only visit one component.

To put the concept into practice, simply follow the below mentioned steps:

  • Declare an array of size V called arr[], where V represents the total number of nodes.
  • The value indicates who the parent of the ith vertex is for each index I of the array arr[].
  • Every node should be created as its own parent, and as they are added together, their parents should be adjusted as necessary.
  • From node 0 through node V, go around them:
  • Start the DSU for each node that is its own parent.
  • Print each node in the disjoint set as though it were a separate component.

Example 2:

#include <bits/stdc++.h>
using namespace std;


int merge(int* parent, int x)
{
    if (parent[x] == x)
        return x;
    return merge(parent, parent[x]);
}


int connectedcomponents(int n, vector >& edges)
{
    int parent[n];
    for (int i = 0; i < n; i++) {
        parent[i] = i;
    }
    for (auto x : edges) {
        parent[merge(parent, x[0])] = merge(parent, x[1]);
    }
    int ans = 0;
    for (int i = 0; i < n; i++) {
        ans += (parent[i] == i);
    }
    for (int i = 0; i < n; i++) {
        parent[i] = merge(parent, parent[i]);
    }
    map > m;
    for (int i = 0; i < n; i++) {
        m[parent[i]].push_back(i);
    }
    for (auto it = m.begin(); it != m.end(); it++) {
        list l = it->second;
        for (auto x : l) {
            cout << x << " ";
        }
        cout << endl;
    }
    return ans;
}


int main()
{
    int n = 5;
    vector e1 = { 0, 1 };
    vector e2 = { 2, 1 };
    vector e3 = { 3, 4 };
    vector > e;
    e.push_back(e1);
    e.push_back(e2);
    e.push_back(e3);


    cout << "Following are connected components:\n";
    int a = connectedcomponents(n, e);
    return 0;
}

Output:

Following are connected components
0 1 2
3 4

Time complexity for the program is - O(V)

Space complexity for the program is - O(V)


Related Topics

How to delete a page in Microsoft Word?

What is Microsoft Word? Microsoft word is a word processing program, which is developed by Microsoft. It was initially launched on 25 October 1983 and has since been modified many times. Generally, Microsoft Word...

2 minutes read.

How to delete Instagram account?

What is Instagram? Instagram is used for sharing the images and videos on social networking websites through various platforms such as iOS, Android, Windows Phones, and Desktop. In 2010, Instagram was...

3 minutes read.

How to Create a Group Email in Gmail

How to Create a Group Email in Gmail Every now and then, one needs to pass on or share a message to several people at the same time. To make this...

6 minutes read.

How to unarchive in Gmail?

How to unarchive in Gmail Earlier, we have learned how to archive an email on a computer or a phone device via the Google app. But archiving is not sufficient; you...

3 minutes read.

How to delete Gmail Account?

What is Gmail? Gmail is a free mobile and web-based email service introduced by Google on April 1, 2004. Gmail is used for personal to business purposes. It allows users to...

2 minutes read.

How to backup iPhone to Computer?

How to backup iPhone to computer iPhone or iPad is an electronic gadget useful to store all preferences, memories, personal or official data, unlike essential documents, emails, messages, photos, running apps,...

6 minutes read.

How to mark all emails as read in Gmail?

How to mark all emails as read in Gmail Gmail is extensively used to exchange official documents, expressions, proposals around the world. In the business industry leaving unread mails is considered...

3 minutes read.

How to create a Gmail account?

How to create a Gmail account? Gmail is a free email service provider widely used worldwide to communicate and exchange personal and professional emails. With almost a billion active users, Gmail...

7 minutes read.

How to flip your Computer Screen

How to flip your computer screen The word flip refers to turn over or rotate something quickly. Computers provide the flip functionality, which facilitates the providers to rotate the screen in...

5 minutes read.

How to accelerate the speed of loading images on any website?

No website can be successful without attractive and relevant images or pictures. In the current time, the users want speedy information about their searches on the internet browser. The image...

3 minutes read.

How to compress jpeg file to 100kb?

Nowadays, everyone loves to share cool snapshots on social media handles. Before putting the images on any site, editing is an integral part. File compression is one of method by...

3 minutes read.

How to defrag a computer?

How to defrag a computer Topics Covered What is Defragmentation?What is the need of defragmentation?Advantages of DefragmentationWhen to defrag your computerDefragmentation for your SSDDefrag your computer running on windows 10Defrag your computer...

8 minutes read.

How to select all in Gmail

How to select all in Gmail Undoubtedly Gmail is one of the leading email service providers across the world. Teenagers, adults, old ages all rely upon Gmail because of its free...

3 minutes read.

How to Multiply Fractions?

What is a Fraction? A fraction is a number that divides a whole number into equal parts. A fraction tells us how many parts we have from the whole part. We...

2 minutes read.

How to address a letter (formal and in-formal)

How to address a letter In the generation of (SMS) and emails, it is still necessary to know how to address a letter for the one. Throughout the modern world, formal letters are...

7 minutes read.

How to add Signature to your Mail

How to add Signature to your Mail Gmail has formed an inevitable aura around the business world. Gmail was launched in the year 2004 as an email service provider with very...

7 minutes read.

How to Cancel Netflix

How to Cancel Netflix Netflix Netflix is a service that lets its members watch a variety of television shows, movies, documentaries, and web series who purchase its subscription. You can enjoy unlimited ad-free...

3 minutes read.

How to find your Computer’s specs?

How to find your computer’s specs The computer specs include the details for every single component in your computer, including your CPU, hard drive space, and even the little things like...

7 minutes read.

How to clean a Computer Screen?

How to clean a computer screen Professionalism is a trait to possess attitude, neatness, and maintenance in every trail of business. Imagine, if you are designated as Marketing Manager, and you...

5 minutes read.

How to find archived emails in Gmail

How to find archived emails in Gmail Similar/Related Questions Where do Gmail archived emails go? How can Gmail users access archived emails? How to get to archived Gmail? In which folder does the archived Gmail...

4 minutes read.