forked from black-shadows/InterviewBit-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCloneGraph.cpp
More file actions
52 lines (49 loc) · 1.61 KB
/
Copy pathCloneGraph.cpp
File metadata and controls
52 lines (49 loc) · 1.61 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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
UndirectedGraphNode* getNode(int x){
return new UndirectedGraphNode (x);
}
UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) {
if(node==NULL)
return node;
unordered_map<UndirectedGraphNode*,bool> vis;
unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> mymap;
queue<UndirectedGraphNode*> Q;
Q.push(node);
vis[node]=1;
while(!Q.empty()){
UndirectedGraphNode *thisnode=Q.front();
Q.pop();
for(int i=0;i<thisnode->neighbors.size();i++){
if(vis.find(thisnode->neighbors[i])==vis.end()){
vis[thisnode->neighbors[i]]=true;
Q.push(thisnode->neighbors[i]);
}
}
mymap[thisnode]=getNode(thisnode->label);
}
Q.push(node);
vis.clear();
vis[node]=1;
while(!Q.empty()){
UndirectedGraphNode *thisnode=Q.front();
UndirectedGraphNode *clone=mymap[thisnode];
Q.pop();
for(int i=0;i<thisnode->neighbors.size();i++){
if(vis.find(thisnode->neighbors[i])==vis.end()){
vis[thisnode->neighbors[i]]=true;
Q.push(thisnode->neighbors[i]);
//cout<<clone->label<<" "<<l<<endl;
}
clone->neighbors.push_back(mymap[thisnode->neighbors[i]]);
}
}
vis.clear();
return mymap[node];
}