Runtime Error! But it works on Eclipse


  • -1
    C

    我用递归的方式去遍历所有nodes,用一个hash map 去记录访问过的node从而防止重复访问,每次遇到一个新的节点node, 把此节点和克隆节点放入hash map, 然后克隆所有此节点的neighbors,完成后,在递归的去克隆neighbors里的节点。
    但是这个case有Runtime error: {0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
    另外,在NetBeans/Eclipse 上跑没有问题!

    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null) return null;
        //use a hashmap to recode visited nodes
        HashMap<UndirectedGraphNode,UndirectedGraphNode> map=new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        UndirectedGraphNode ret=new UndirectedGraphNode(node.label);
        clone(node, ret, map);
        return ret;
    }
    void clone(UndirectedGraphNode node, UndirectedGraphNode cln, HashMap<UndirectedGraphNode,UndirectedGraphNode> map){
        if(!map.containsKey(node)){
            map.put(node,cln);
            //this hash map is used to avoid keeping create the same sub node again and again.(eg. 1,2,2,2 )
            HashMap<UndirectedGraphNode,UndirectedGraphNode> subs=new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
            for(UndirectedGraphNode n: node.neighbors){
                if(map.containsKey(n)){//means that node point to itself
                    cln.neighbors.add(map.get(n));
                }else{
                   if(subs.containsKey(n)){//if it's the same subnode then add it again instead of creating a new one
                       cln.neighbors.add(map.get(n));
                   }else{
                       UndirectedGraphNode newNode=new UndirectedGraphNode(n.label);
                       cln.neighbors.add(newNode); 
                       subs.put(n,newNode);                       
                   }
                }
            }
            //clone current node's neighbors
            for(int i=0;i<node.neighbors.size();i++){
                clone(node.neighbors.get(i),cln.neighbors.get(i),map);
            }
        }//end of if
    }

Log in to reply
 

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