-
Notifications
You must be signed in to change notification settings - Fork 213
/
Connected_Components.cpp
71 lines (55 loc) · 1.54 KB
/
Connected_Components.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* By Aditya Raj */
// ------------- //
/*
Program to counted number of connected components in an
Undirected Graph using DFS (Depth First Search)
*/
#include <bits/stdc++.h>
using namespace std;
#define MAXN 200001 // Defining the maximum value to be 200001
// 'adj' is a Vector of Vector to store connected nodes in form of Adjacency List
vector<vector<int>>adj;
// 'visited' is a Vector to keep track of visited nodes (initially all are unvisited)
vector<int>visited(MAXN, 0);
int n, m; // Variables for nodes and edges
// DFS function
void dfs(int v)
{
visited[v] = 1; // Marking the nodes as visited
for(auto i:adj[v])
{
if(!visited[i])
{
dfs(i); // if the connected node is not visited calling dfs function again
}
}
return;
}
// Main function
int main()
{
cin>>n>>m; // taking input number of nodes and edges of the Graph
adj.resize(n + 1); // Resizing the Vector of Vector
for(int i = 0;i < m;i++)
{
int x, y;
cin>>x>>y;
// Storing the nodes of Undirected Graph in form of Adjacency list
adj[x].push_back(y);
adj[y].push_back(x);
}
int cnt = 0;
for(int i = 1;i <= n;i++)
{
// If node is not visited then calling DFS function
if(visited[i])
{
continue;
}
dfs(i);
cnt++; // counting the number of connected components of the Undirected Graph
}
// Printing out the number of connected components
cout<<cnt;
return 0;
}