forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-the-connected-component-in-the-undirected-graph(AC).cpp
More file actions
71 lines (67 loc) · 1.73 KB
/
find-the-connected-component-in-the-undirected-graph(AC).cpp
File metadata and controls
71 lines (67 loc) · 1.73 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <unordered_map>
using namespace std;
/**
* 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) {
int n = nodes.size();
int i;
dj.resize(n);
for (i = 0; i < n; ++i) {
dj[i] = i;
um[nodes[i]] = i;
}
int j;
int x, y, rx, ry;
for (i = 0; i < n; ++i) {
x = um[nodes[i]];
for (j = 0; j < nodes[i]->neighbors.size(); ++j) {
y = um[nodes[i]->neighbors[j]];
rx = findRoot(x);
ry = findRoot(y);
dj[rx] = ry;
}
}
vector<vector<int> > ans;
unordered_map<int, vector<int> > cc;
unordered_map<int, vector<int> >::iterator it;
for (i = 0; i < n; ++i) {
findRoot(i);
cc[dj[i]].push_back(nodes[i]->label);
}
for (it = cc.begin(); it != cc.end(); ++it) {
ans.push_back(it->second);
}
dj.clear();
um.clear();
cc.clear();
return ans;
}
private:
vector<int> dj;
unordered_map<UndirectedGraphNode*, int> um;
int findRoot(int x) {
int r = x;
while (r != dj[r]) {
r = dj[r];
}
int k = x;
while (x != r) {
x = dj[x];
dj[k] = r;
k = x;
}
return r;
}
};