[LeetCode] Clone Graph

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

Clone Graph

BFS

Time Complexity
O(N)
Space Complexity
O(N)

思路

Do a BFS traversal of the graph and while visiting a node make a clone node of it.

Use a hashmap to check if the node has already been created.
Key value: reference of original node
Value: reference of cloned node

How to connect clone nodes?
After all graph nodes has been made, get the corresponding cloned node u, then visit all the neighboring nodes of u and then connect the corresponding clone node then push it into queue.

代码

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    //coner case
    if(node == null) return null;
    Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
    Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
    queue.offer(node);
    UndirectedGraphNode root = new UndirectedGraphNode(node.label);
    map.put(node, root);
    while(!queue.isEmpty()){
        UndirectedGraphNode cur = queue.poll();
        for(UndirectedGraphNode n : cur.neighbors){
            if(!map.containsKey(n)){
                map.put(n, new UndirectedGraphNode(n.label));
                queue.offer(n);
            }
            map.get(cur).neighbors.add(map.get(n));
        }
    }
    return root;
}

DFS

Time Complexity
O(N)
Space Complexity
O(N)

思路

You can think it as a tree, the level is how many nodes in the graph, each level represents all the neighbors of the nodes, after create all cloned nodes, then connect them together. Use the hashmap method as BFS method.

代码

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    if(node == null) return node;
    Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
    UndirectedGraphNode root = new UndirectedGraphNode(node.label);
    map.put(node, root);
    helper(node, map);
    return root;
}

private void helper(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map){
    for(UndirectedGraphNode n : node.neighbors){
        if(!map.containsKey(n)){
            map.put(n, new UndirectedGraphNode(n.label));
            helper(n, map);
        }
        map.get(node).neighbors.add(map.get(n));
    }
}

脚本宝典总结

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

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

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