133. Clone Graph

发布时间:2019-06-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了133. Clone Graph脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.

OJ's undirected graph serialization (so you can understand error output):
Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
      / 
     /   
    0 --- 2
         / 
         _/

Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don't need to understand the serialization to solve the problem.

难度:medium

题目:给定一图的头结点,返回其深拷贝。每个结点包含一个标签及一组邻结点。在给定的结点与其邻结点之间都有一边。

思路:BFS

Runtime: 6 ms, faster than 19.61% of Java online submissions for Clone Graph.
Memory Usage: 37.9 MB, less than 95.96% of Java online submissions for Clone Graph.

/**
 * 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 (null == node) {
            return null;
        }
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        queue.add(node);
        Map<UndirectedGraphNode, UndirectedGraphNode> nodes = new HashMap<>();
        
        while (!queue.isEmpty()) {
            UndirectedGraphNode tNode = queue.poll();
            nodes.put(tNode, new UndirectedGraphNode(tNode.label));
            
            for (UndirectedGraphNode n: tNode.neighbors) {
                if (!nodes.containsKey(n)) {
                    queue.add(n);
                }
            }
        }
        
        for (Map.Entry<UndirectedGraphNode, UndirectedGraphNode> e: nodes.entrySet()) {
            UndirectedGraphNode copyNode = e.getValue();
            for (UndirectedGraphNode n : e.getKey().neighbors) {
                copyNode.neighbors.add(nodes.get(n));
            }
        }
        
        return nodes.get(node);
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的133. Clone Graph全部内容,希望文章能够帮你解决133. Clone Graph所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: