forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.cpp
More file actions
38 lines (38 loc) · 1.31 KB
/
CloneGraph.cpp
File metadata and controls
38 lines (38 loc) · 1.31 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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node==NULL) {
return NULL;
}
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> oldToNew;
queue<UndirectedGraphNode*> q;
q.push(node);
UndirectedGraphNode* node1 = new UndirectedGraphNode(node->label);
oldToNew[node] = node1;
while(!q.empty()) {
UndirectedGraphNode* top = q.front();
q.pop();
UndirectedGraphNode* top1 = oldToNew[top];
for(int i=0;i<top->neighbors.size();i++) {
if(oldToNew.find(top->neighbors[i]) == oldToNew.end()) {
UndirectedGraphNode* n = new UndirectedGraphNode(top->neighbors[i]->label);
oldToNew[top->neighbors[i]] = n;
top1->neighbors.push_back(n);
q.push(top->neighbors[i]);
} else {
UndirectedGraphNode* n = oldToNew[top->neighbors[i]];
top1->neighbors.push_back(n);
}
}
}
return node1;
}
};