Clone a graph

Deep-copy a connected graph. A map from original node to its clone stops cycles from causing infinite recursion.

Time O(V + E)Space O(V)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

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;
}

Tips

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.