Simple solution


  • 0

    I am not sure why so many guys prefer complicated solution.

    Note that in the question, all the node labels are unique. We can use a simple <Integer, Node> map to mark visited, and DFS to traverse the original graph.

    To avoid cycle, remember to put in map before adding neighbors.

    Map<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
    
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        if(map.containsKey(node.label)) {
            return map.get(node.label);
        }
        
        UndirectedGraphNode cloned = new UndirectedGraphNode(node.label);
        map.put(node.label, cloned);       
        for(UndirectedGraphNode nb : node.neighbors) {
            cloned.neighbors.add(cloneGraph(nb));
        }
        return cloned;
    }

  • 0

    "cannot be simpler"

    It can be a bit simpler.

    You could just use the nodes as keys instead of the labels of the nodes. As a nice side effect, you then also wouldn't rely on labels being unique.

    Could also a little more code, though I guess it's debatable what is simpler.


  • 0

    Yeah I agree with you Stefan. Simplicity can have different aspects. Let me change the title really quick :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.