Node with label 1 was not copied but a reference to the original one.


  • 0
    B

    Hi I am getting following output.

    Input: {-1,1#1}

    Output: Node with label 1 was not copied but a reference to the original one.

    Expected: {-1,1#1}

    can't figure out the problem.

     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
              if(node==null)
              {
            	  return null;
              }
              else
              {
            	  Map<UndirectedGraphNode,UndirectedGraphNode> visited  = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
            	  Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
            	  UndirectedGraphNode newHead = new UndirectedGraphNode(node.label);
            	  UndirectedGraphNode currNode = null;
            	  visited.put(node, newHead);
            	    queue.add(node);
            	  while(!queue.isEmpty())
            	  {
            		  currNode=queue.poll();
            			List<UndirectedGraphNode> neighbors=currNode.neighbors;
            		  for(UndirectedGraphNode neb : neighbors)
            		  {
            			if(!visited.containsKey(neb))
            		  {
            			  UndirectedGraphNode copy = new UndirectedGraphNode(neb.label);
            			  visited.put(neb, copy);
            			  visited.get(currNode).neighbors.add(neb);
            			  queue.add(neb);
            		  }
            		  else
            		  {
            			  visited.get(currNode).neighbors.add(visited.get(neb));
            		  }
            		  }
            	  }
            	  return newHead;  
              }
        	}

Log in to reply
 

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