-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path05.ConnectedComponents.cpp
More file actions
38 lines (32 loc) · 891 Bytes
/
05.ConnectedComponents.cpp
File metadata and controls
38 lines (32 loc) · 891 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void dfs(int node, vector<vector<int>>& adj, vector<bool>& visited) {
visited[node] = true;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited);
}
}
}
int countComponents(int V, vector<vector<int>>& edges) {
vector<vector<int>> adj(V);
// Build adjacency list
for (auto &edge : edges) {
int u = edge[0];
int v = edge[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<bool> visited(V, false);
int count = 0;
for (int i = 0; i < V; i++) {
if (!visited[i]) {
dfs(i, adj, visited);
count++;
}
}
return count;
}
};