[Geeks for Geeks] Clone Graph

Clone Graph

Given a reference of a node in a connected undirected graph. Return a clone of the graph.
Each node in the graph contains a value (Integer) and a list (List[Node]) of its neighbors.

  • Time : O(v + e)
  • Space : O(v)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
unordered_map<Node*, Node*> mp;
Node* helper(Node* node) {
if(mp.count(node)) return mp[node];
mp[node] = new Node(node->val);
for(auto& n : node->neighbors) {
mp[node]->neighbors.push_back(helper(n));
}
return mp[node];
}
public:
Node* cloneGraph(Node* node) {
mp.clear();
return helper(node);
}
};

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