美文网首页
133. Clone Graph

133. Clone Graph

作者: greatseniorsde | 来源:发表于2018-02-07 15:28 被阅读0次

    第一步加到map里面value是null只是为了去重,下一次遇到就不会进queue

    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null){
                return null;
            }        
            Queue<UndirectedGraphNode> queue = new LinkedList<>();
            Map<UndirectedGraphNode, UndirectedGraphNode> visited = new HashMap<>();
            queue.offer(node);
            visited.put(node, null);
            while (!queue.isEmpty()){
                UndirectedGraphNode curt = queue.poll();
                UndirectedGraphNode copy = new UndirectedGraphNode(curt.label);
                visited.put(curt, copy);
                for (UndirectedGraphNode nei : curt.neighbors){
                    if (!visited.containsKey(nei)){
                        queue.offer(nei);
                        visited.put(nei, null);
                    }
                }
            }
            for (UndirectedGraphNode orig : visited.keySet()){
                UndirectedGraphNode copy = visited.get(orig);
                for (UndirectedGraphNode nei : orig.neighbors){
                    copy.neighbors.add(visited.get(nei));
                }
            }
            return visited.get(node);
        }
    }
    

    相关文章

      网友评论

          本文标题:133. Clone Graph

          本文链接:https://www.haomeiwen.com/subject/tkfazxtx.html