-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone Graph.cpp
More file actions
44 lines (44 loc) · 1.56 KB
/
Clone Graph.cpp
File metadata and controls
44 lines (44 loc) · 1.56 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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(node == NULL)
return NULL;
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> Hash;
UndirectedGraphNode *root = new UndirectedGraphNode(node->label);
Hash.insert({node, root});
queue<UndirectedGraphNode *> Q;
Q.push(node);
while(!Q.empty())
{
UndirectedGraphNode *now = Q.front();
Q.pop();
UndirectedGraphNode *clone_now = Hash.find(now)->second;
for(int i = 0; i < now->neighbors.size(); ++i)
{
UndirectedGraphNode *next = now->neighbors[i];
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>::iterator search = Hash.find(next);
if(search == Hash.end())
{
UndirectedGraphNode *clone_next = new UndirectedGraphNode(next->label);
Hash.insert({next, clone_next});
Q.push(next);
clone_now->neighbors.push_back(clone_next);
}
else
{
clone_now->neighbors.push_back(search->second);
}
}
}
return root;
}
};