In: Computer Science
#include <bits/stdc++.h>
using namespace std;
void dfs(int currNode, int par, vector<vector<int>> &adj, vector<bool> &vis)
{
vis[currNode] = true;
for(int i : adj[currNode])
{
if(i == par || vis[i])
continue;
dfs(i, currNode, adj, vis);
}
}
int main()
{
int numNodes, numEdges;
cin >> numNodes >> numEdges;
vector<vector<int>> adj(numNodes + 1); // adjency list for storing graph
for(int i = 0; i < numEdges; i++)
{
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
vector<bool> visited(numNodes + 1, 0); // for marking visited nodes
int numComponents = 0;
for(int i = 1; i <= numNodes; i++)
{
// iterating over all nodes
// and if node is already visited(means it already occured in some component)
// then we'll skip else, we'll explore this component and increment the numComponennt counter.
if(visited[i])
continue;
dfs(i, 0, adj, visited);
numComponents++;
}
cout << numComponents << "\n";
return 0;
}
Create a new cpp file and name it as Solution.cpp and copy paste this code and submit it.