-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloneGraph.cpp
33 lines (28 loc) · 1007 Bytes
/
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
/* Code challenge #133 from LeetCode */
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode* DFS(UndirectedGraphNode* node, std::unordered_map<int, UndirectedGraphNode*>& hashmap) {
if (hashmap.find(node->label) != hashmap.end())
return hashmap[node->label];
UndirectedGraphNode* new_node = new UndirectedGraphNode(node->label);
hashmap.insert(make_pair(new_node->label, new_node));
for (auto neighbor : node->neighbors) {
new_node->neighbors.push_back(DFS(neighbor, hashmap));
}
return new_node;
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node)
return nullptr;
std::unordered_map<int, UndirectedGraphNode*> hashmap;
return DFS(node, hashmap);
}
};