Clone a graph
Deep-copy a connected graph. A map from original node to its clone stops cycles from causing infinite recursion.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
DFS (or BFS) from the start node, but before recursing into a neighbour check a map keyed by the original node. If the neighbour is already in the map, reuse its clone instead of recursing again; this is what keeps a cycle from looping forever.
Code
public static Node CloneGraph(Node start) {
var map = new Dictionary<Node, Node>();
return Clone(start, map);
}
static Node Clone(Node node, Dictionary<Node, Node> map) {
if (map.TryGetValue(node, out var existing)) return existing;
var copy = new Node(node.Val);
map[node] = copy;
foreach (var n in node.Neighbors)
copy.Neighbors.Add(Clone(n, map));
return copy;
}static Node cloneGraph(Node start) {
Map<Node, Node> map = new HashMap<>();
return clone(start, map);
}
static Node clone(Node node, Map<Node, Node> map) {
Node existing = map.get(node); if (existing != null) return existing;
Node copy = new Node(node.val);
map.put(node, copy);
for (Node n : node.neighbors)
copy.neighbors.add(clone(n, map));
return copy;
}Node* clone(Node* node, unordered_map<Node*, Node*>& copies) {
if (auto it = copies.find(node); it != copies.end()) return it->second;
Node* copy = new Node(node->val);
copies[node] = copy;
for (Node* n : node->neighbors)
copy->neighbors.push_back(clone(n, copies));
return copy;
}
Node* cloneGraph(Node* start) {
unordered_map<Node*, Node*> copies;
return clone(start, copies);
}def clone_graph(start: Node) -> Node:
copies: dict[Node, Node] = {}
return clone(start, copies)
def clone(node: Node, copies: dict[Node, Node]) -> Node:
if node in copies: return copies[node]
copy = Node(node.val)
copies[node] = copy
for n in node.neighbors:
copy.neighbors.append(clone(n, copies))
return copyTips
- Populate the map entry for a node before recursing into its neighbours, in case one of them points back to it.
- The same idea works with BFS: queue a node only the first time it is added to the map.
In the .NET library
This is identical to the seen-set used in plain DFS, except the set is now a dictionary that also carries the payload (the clone) for each key.