-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone_Graph.cpp
More file actions
59 lines (53 loc) · 1.55 KB
/
Clone_Graph.cpp
File metadata and controls
59 lines (53 loc) · 1.55 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "vector"
#include "queue"
#include "unordered_map"
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
class Solution {
public:
Node* cloneGraph(Node* node) {
if (node == nullptr) {
return nullptr;
}
queue <Node*> q;
// copy of graph as a map: key = original node, value = copied node using new
unordered_map<Node*, Node*> gCopy;
// Load given root node into queue and make a copy
q.push(node);
Node* newRoot = new Node(node->val);
gCopy[node] = newRoot;
// BFS
while(!q.empty()) {
Node* temp = q.front();
q.pop();
for (int i=0; i<temp->neighbors.size(); i++) {
if (gCopy.find(temp->neighbors[i]) == gCopy.end()) {
// node has not been copied or visited yet
gCopy[temp->neighbors[i]] = new Node(temp->neighbors[i]->val);
q.push(temp->neighbors[i]);
}
// insert neighbor of copied node. This is irrespective of whether the node has
// been visited already
gCopy[temp]->neighbors.push_back(gCopy[temp->neighbors[i]]);
}
}
return newRoot;
}
};