-
Notifications
You must be signed in to change notification settings - Fork 0
/
323. Number of Connected Components in an Undirected Graph.cpp
54 lines (52 loc) · 1.46 KB
/
323. Number of Connected Components in an Undirected Graph.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
// DFS
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<vector<int>>graph(n);
vector<int>visited(n);
for(auto x: edges){
graph[x.first].push_back(x.second);
graph[x.second].push_back(x.first);
}
int label = 0;
for(int i = 0; i < n; i++){
if(visited[i]) continue;
label++;
DFS(graph, i, visited);
}
return label;
}
void DFS(vector<vector<int>>& graph, int root, vector<int>& visited){
if(visited[root]) return;
visited[root] = 1;
for(auto neigh: graph[root])
if(!visited[neigh]) DFS(graph, neigh, visited);
}
};
// BFS
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<vector<int>>graph(n);
vector<int>visited(n);
for(auto x: edges){
graph[x.first].push_back(x.second);
graph[x.second].push_back(x.first);
}
int label = 0;
for(int i = 0; i < n; i++){
if(visited[i]) continue;
label++;
deque<int>q;
q.push_back(i);
while(!q.empty()){
int node = q.front();
q.pop_front();
visited[node] = 1;
for(auto neigh: graph[node])
if(!visited[neigh]) q.push_back(neigh);
}
}
return label;
}
};