Algo-Sim › Graph Traversal

Clone Graph

Medium · Graph Traversal · step through it in Java, Python and C++ on your own input

Return a deep copy of a connected undirected graph. DFS with a map from each original node to its copy, filled before visiting neighbours.

Problem

Given a node of a connected undirected graph, where each node has a value and a list of neighbours, return a deep copy of the whole graph: new nodes with the same values and the same connections, sharing nothing with the original.

Constraints

Edge cases to test

Follow-up questions

Why put the copy in the map before visiting neighbours?
A cycle leads back to the node; finding its copy in the map stops infinite recursion.
DFS or BFS?
Either: both visit each node and edge once, O(V + E). BFS avoids deep recursion.

Solution

Java

private Map<Node, Node> clones = new HashMap<>();

public Node cloneGraph(Node node) {
    if (node == null) return null;
    if (clones.containsKey(node)) return clones.get(node);
    Node copy = new Node(node.val);
    clones.put(node, copy);
    for (Node next : node.neighbors) {
        copy.neighbors.add(cloneGraph(next));
    }
    return copy;
}

Python

clones = {}


def clone_graph(node):
    if node is None:
        return None
    if node in clones:
        return clones[node]
    copy = Node(node.val)
    clones[node] = copy
    for nxt in node.neighbors:
        copy.neighbors.append(clone_graph(nxt))
    return copy

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    unordered_map<Node *, Node *> clones = {};

    Node *cloneGraph(Node *node) {
        if (node == nullptr)
            return nullptr;
        if (clones.count(node))
            return clones[node];
        Node *copy = new Node(node->val);
        clones[node] = copy;
        for (Node *next : node->neighbors) {
            copy->neighbors.push_back(cloneGraph(next));
        }
        return copy;
    }
};

More Graph Traversal problems