[InterviewBit] Clone Graph

Clone Graph

  • Time :
  • Space :
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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
void dfs(UndirectedGraphNode* node, unordered_map<int, UndirectedGraphNode*>& copy) {
copy[node->label] = new UndirectedGraphNode(node->label);
for(auto v : node->neighbors) {
if(copy.count(v->label)) continue;
dfs(v, copy);
}
}
void dfs2(UndirectedGraphNode* node, unordered_map<int, UndirectedGraphNode*>& copy, unordered_set<int>& vis) {
vis.insert(node->label);
for(auto v : node->neighbors) {
copy[node->label]->neighbors.push_back(copy[v->label]);
if(!vis.count(v->label)) dfs2(v, copy, vis);
}
}
UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) {
unordered_map<int, UndirectedGraphNode*> copy;
dfs(node, copy);
dfs2(node, copy, unordered_set<int>() = {});
return copy[node->label];
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/03/PS/interviewbit/clone-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.