-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path323-components-in-undirected-graph.cpp
46 lines (43 loc) · 1.3 KB
/
323-components-in-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
#include <unordered_map>
#include <queue>
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
unordered_map<int, vector<int>> graph;
unordered_map<int, bool> visited;
for (int i = 0; i < n; i++) {
graph[i] = {};
visited[i] = false;
}
for (vector<int> v : edges) {
int from = v[0];
int to = v[1];
graph[from].push_back(to);
graph[to].push_back(from);
}
int result = 0;
int numVisited = 0;
auto it = graph.begin();
while (numVisited < n) {
int node = it->first;
if (!visited[node]) {
queue<int> q;
q.emplace(node);
while (!q.empty()) {
int currNode = q.front();
q.pop();
visited[currNode] = true;
numVisited++;
for (int neighbor : it->second) {
if (!visited[neighbor]) {
q.emplace(neighbor);
}
}
}
result++;
}
it++;
}
return result;
}
};