Concise Java solution using DFS and HashMap

  • 0
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if(node == null) return node;
            HashMap<Integer,UndirectedGraphNode> map = new HashMap<>();
            return clone(node,map);
        private UndirectedGraphNode clone(UndirectedGraphNode node, HashMap<Integer,UndirectedGraphNode> map ){
            if(!map.containsKey(node.label)){ // keeping track of visited nodes
                UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
                for(UndirectedGraphNode each : node.neighbors )
                    copy.neighbors.add(clone(each,map)); // recursive DFS
            return map.get(node.label);

Log in to reply

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