Java 2 solutions, bfs & dfs


  • 4
    M

    bfs:
    Use queue to record old node, and hashmap to record new node.

        private UndirectedGraphNode bfs(UndirectedGraphNode node){
            if(node==null) return null;
            Queue<UndirectedGraphNode> que = new LinkedList<>(); // old node
            Map<Integer, UndirectedGraphNode> map = new HashMap<>(); // new node
            UndirectedGraphNode root = new UndirectedGraphNode(node.label);
            map.put(root.label, root);
            que.offer(node);
            UndirectedGraphNode p = root, newRoot = root, newNode = root;
            while(!que.isEmpty()){
                p = que.poll();
                newRoot = map.get(p.label);
                for(UndirectedGraphNode n : p.neighbors){
                    if(map.containsKey(n.label)){
                        newNode = map.get(n.label);
                    } else{
                        newNode = new UndirectedGraphNode(n.label);
                        map.put(newNode.label, newNode);
                        que.offer(n);
                    }
                    newRoot.neighbors.add(newNode);
                }
            }
            return root;
        }
    

    dfs

        private UndirectedGraphNode dfs(UndirectedGraphNode node, Map<Integer, UndirectedGraphNode> map){
            if(node == null) return null;
            UndirectedGraphNode newNode = map.get(node.label);
            if(newNode != null) 
                return newNode;
            newNode = new UndirectedGraphNode(node.label);
            map.put(newNode.label, newNode);
            for(UndirectedGraphNode v : node.neighbors){
                newNode.neighbors.add( dfs(v, map) );
            }
            return newNode;
        }
    

Log in to reply
 

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