-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphCloning.cpp
62 lines (45 loc) · 1.75 KB
/
GraphCloning.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
private:
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> myMap;
public:
//DFS Solution to the graph cloning
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
if(myMap.find(node) == myMap.end()){
myMap[node] = new UndirectedGraphNode(node->label);
for(UndirectedGraphNode* nodes: node->neighbors){
myMap[node]->neighbors.push_back(cloneGraph(nodes));
}
}
return myMap[node];
}
//BFS Solution to the graph cloning
UndirectedGraphNode *cloneGraphBFS(UndirectedGraphNode *node) {
if(!node) return NULL;
UndirectedGraphNode * newNode = new UndirectedGraphNode(node->label);
myMap[node] = newNode;
queue<UndirectedGraphNode*> myQueue;
myQueue.push(node);
while(!myQueue.empty()){
UndirectedGraphNode * temp = myQueue.front();
myQueue.pop();
for(auto neigh: temp->neighbors){
if (myMap.find(neigh) == myMap.end()) {
UndirectedGraphNode* neigh_copy = new UndirectedGraphNode(neigh -> label);
myMap[neigh] = neigh_copy;
myQueue.push(neigh);
}
myMap[temp]->neighbors.push_back(myMap[neigh]);
}
}
return newNode;
}
};