-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.cpp
47 lines (40 loc) · 1.56 KB
/
CloneGraph.cpp
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
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<int, UndirectedGraphNode*> track;
return cloneGraph(node, track);
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode *>& track)
{
if(!node) return NULL;
if(track.count(node->label)) return track[node->label];
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
new_node->neighbors.resize(node->neighbors.size());
track[node->label] = new_node;
for(int i = 0; i < node->neighbors.size(); i++)
{
new_node->neighbors[i] = cloneGraph(node->neighbors[i], track);
}
return new_node;
}
};
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<int, UndirectedGraphNode*> track;
return cloneGraph(node, track);
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode *>& track)
{
if(!node) return NULL;
if(track.count(node->label)) return track[node->label];
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
// new_node->neighbors.resize(node->neighbors.size());
track[node->label] = new_node;
for(int i = 0; i < node->neighbors.size(); i++)
{
new_node->neighbors.push_back(cloneGraph(node->neighbors[i], track));
}
return new_node;
}
};