-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133.cpp
43 lines (37 loc) · 1.05 KB
/
133.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
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
if(!node) return NULL;
Node* copy = new Node(node->val, {});
unordered_map<Node*, Node*> nodeMap;
nodeMap[node] = copy;
queue<Node*> nodeQueue;
nodeQueue.push(node);
while(!nodeQueue.empty()) {
auto cur = nodeQueue.front();
nodeQueue.pop();
for(auto& c : cur->neighbors) {
if(!nodeMap.count(c)) {
Node* copyC = new Node(c->val, {});
nodeMap[c] = copyC;
nodeQueue.push(c); // this line of code should be inside the if statement, else time limit exceeded, using hashtable as visited array
}
nodeMap[cur]->neighbors.push_back(nodeMap[c]);
}
}
return copy;
}
};