-
Notifications
You must be signed in to change notification settings - Fork 258
/
clone-graph.cpp
42 lines (38 loc) · 1.11 KB
/
clone-graph.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
// Time: O(|V| + |E|)
// Space: O(|V|)
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) {
return nullptr;
}
unordered_map<const UndirectedGraphNode *, UndirectedGraphNode *> copied;
copied[node] = new UndirectedGraphNode(node->label);
queue<const UndirectedGraphNode *> q;
q.emplace(node);
while (!q.empty()) {
auto node = q.front();
q.pop();
for (const auto& n : node->neighbors) {
if (copied.find(n) == copied.end()) {
copied[n] = new UndirectedGraphNode(n->label);
q.emplace(n);
}
copied[node]->neighbors.emplace_back(copied[n]);
}
}
return copied[node];
}
};