-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathfind-the-connected-component-in-the-undirected-graph.cpp
48 lines (44 loc) · 1.42 KB
/
find-the-connected-component-in-the-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
// Time: O(n)
// Space: O(n)
/**
* Definition for Undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param nodes a array of Undirected graph node
* @return a connected set of a Undirected graph
*/
vector<vector<int>> connectedSet(vector<UndirectedGraphNode*>& nodes) {
vector<vector<int>> components;
queue<UndirectedGraphNode*> q;
unordered_set<UndirectedGraphNode*> visited;
for (const auto& node : nodes) {
if (visited.find(node) == visited.end()) {
visited.emplace(node);
q.emplace(node);
vector<int> component;
while (!q.empty()) {
auto node = q.front();
q.pop();
component.emplace_back(node->label);
for (const auto& n : node->neighbors) {
if (visited.find(n) == visited.end()) {
visited.emplace(n);
q.emplace(n);
}
}
}
// Sort component.
sort(component.begin(), component.end());
components.emplace_back(move(component));
}
}
return components;
}
};