forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloneGraph.cpp
More file actions
26 lines (26 loc) · 831 Bytes
/
cloneGraph.cpp
File metadata and controls
26 lines (26 loc) · 831 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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
map<int, UndirectedGraphNode*> vv;
UndirectedGraphNode* doit(UndirectedGraphNode *v) {
UndirectedGraphNode *res = new UndirectedGraphNode(v->label);
vv[v->label] = res;
for (int i = 0; i < v->neighbors.size(); ++i) {
if (!vv[v->neighbors[i]->label]) res->neighbors.push_back(doit(v->neighbors[i]));
else res->neighbors.push_back(vv[v->neighbors[i]->label]);
}
return res;
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) return NULL;
vv.clear();
return doit(node);
}
};