Accepted breadth first search solution


  • 0
    J
      public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            
            if(node==null)
                return null;
            
            HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
            LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
    
            int headlabel=node.label;
            UndirectedGraphNode newNode = new UndirectedGraphNode(headlabel);
            map.put(headlabel, newNode);
            
            UndirectedGraphNode curNode = node;
            do{
                newNode = map.get(curNode.label);
                for(UndirectedGraphNode oneNode: curNode.neighbors){
                    if(!map.containsKey(oneNode.label)){
                        map.put(oneNode.label, new UndirectedGraphNode(oneNode.label));
                        queue.add(oneNode);
                    }
                    newNode.neighbors.add(map.get(oneNode.label));
                }
                curNode = queue.poll();
            }while(curNode!=null);
             
            return map.get(headlabel);
        }

Log in to reply
 

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