-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathClone Graph.cpp
More file actions
31 lines (27 loc) · 861 Bytes
/
Clone Graph.cpp
File metadata and controls
31 lines (27 loc) · 861 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
27
28
29
30
31
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) {
unordered_map<int,UndirectedGraphNode*>m;
queue<UndirectedGraphNode *> q;
q.push(node);
UndirectedGraphNode * n=new UndirectedGraphNode(node->label);
m[node->label]=n;
while(!q.empty()){
UndirectedGraphNode* t=q.front();
q.pop();
for(auto i:t->neighbors){
if(m.find(i->label)==m.end()){
m[i->label]=new UndirectedGraphNode(i->label);
q.push(i);
}
(m[t->label]->neighbors).push_back(m[i->label]);
}
}
return m[node->label];
}