forked from Anchor89/LeetCodeAnchor89
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloneGraph.cpp
35 lines (33 loc) · 972 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
34
35
#include "LeetCode.h"
class Solution {
public:
using Node = UndirectedGraphNode;
Node* getOther(unordered_map<Node*, Node*>& shadow, Node* ori) {
if (ori == nullptr) return nullptr;
if (shadow.find(ori) == shadow.end()) {
shadow.insert(make_pair(ori, new Node(ori->label)));
}
return shadow.find(ori)->second;
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == nullptr) return nullptr;
unordered_map<Node*, Node*> shadow;
queue<Node*> q;
unordered_set<Node*> visited;
q.push(node);
visited.insert(node);
while(!q.empty()) {
Node* cur = q.front();
q.pop();
Node* other = getOther(shadow, cur);
for (auto adj : cur->neighbors) {
other->neighbors.push_back(getOther(shadow, adj));
if (visited.find(adj) == visited.end()) {
visited.insert(adj);
q.push(adj);
}
}
}
return getOther(shadow, node);
}
};