Short Java DFS - 5ms


  • 0
    V
        HashMap<Integer, UndirectedGraphNode> hm = new HashMap<Integer, UndirectedGraphNode>();
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) 
        {
            if(node == null)
                return null;
            if(hm.containsKey(node.label))
                return hm.get(node.label);
            UndirectedGraphNode undirectedGraphNode = new UndirectedGraphNode(node.label);
            hm.put(node.label, undirectedGraphNode);        
            for(int i = 0; i < node.neighbors.size(); i++)
                undirectedGraphNode.neighbors.add(cloneGraph(node.neighbors.get(i)));
            return undirectedGraphNode;
        }

Log in to reply
 

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