-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.cpp
More file actions
49 lines (39 loc) · 1.2 KB
/
CloneGraph.cpp
File metadata and controls
49 lines (39 loc) · 1.2 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
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == nullptr) {
return node;
}
typedef unordered_map<int, UndirectedGraphNode*> LABEL_MAP_NODE;
LABEL_MAP_NODE Graph;
LABEL_MAP_NODE CloneGraph;
queue<UndirectedGraphNode* > NodeQueue;
NodeQueue.push(node);
while (!NodeQueue.empty()) {
int val = NodeQueue.front()->label;
if (Graph.find(val) != Graph.end()) {
NodeQueue.pop();
continue;
}
Graph[val] = NodeQueue.front();
for (auto Gnode : NodeQueue.front()->neighbors) {
NodeQueue.push(Gnode);
}
CloneGraph[val] = new(std::nothrow)UndirectedGraphNode(val);
assert(CloneGraph[val]);
NodeQueue.pop();
}
for (auto NodePair : Graph) {
int val = NodePair.first;
for (auto Gnode : NodePair.second->neighbors) {
CloneGraph[val]->neighbors.push_back(CloneGraph[Gnode->label]);
}
}
return CloneGraph[node->label];
}
};