Problem: Clone Graph

Posted by Marcy on February 18, 2015

Question

Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

Solution

TODO

Code

class Solution {
    Map<Node, Node> clonedNodes = new HashMap<>();
    public Node cloneGraph(Node node) {
        if(clonedNodes.containsKey(node)) return clonedNodes.get(node);
        Node clonedNode = new Node();
        clonedNode.val = node.val;
        clonedNode.neighbors = new ArrayList<>();
        clonedNodes.put(node, clonedNode);
        for(Node nei: node.neighbors) {
            clonedNode.neighbors.add(cloneGraph(nei));
        }
        return clonedNode;
    }
}

Performance

TODO