算法常考真题详解:克隆图

简介: 算法面试真题详解:克隆图

克隆一张无向图. 无向图的每个节点包含一个 label 和一个列表 neighbors. 保证每个节点的 label 互不相同.
你的程序需要返回一个经过深度拷贝的新图. 新图和原图具有同样的结构, 并且对新图的任何改动不会对原图造成任何影响.
你需要返回与给定节点具有相同 label 的那个节点.

说明
关于无向图的表示

在线评测地址:领扣题库官网

样例1:
输入:
{1,2,4#2,1,4#4,1,2}
输出: 
{1,2,4#2,1,4#4,1,2}
解释:
1------2  
 \     |  
  \    |  
   \   |  
    \  |  
      4   

思路

从原图给定的点找到所有点
复制所有的点
复制所有的边

题解:

public class Solution {
    /**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return node;
        }

        // use bfs algorithm to traverse the graph and get all nodes.
        ArrayList<UndirectedGraphNode> nodes = getNodes(node);

        // copy nodes, store the old->new mapping information in a hash map
        HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
        for (UndirectedGraphNode n : nodes) {
            mapping.put(n, new UndirectedGraphNode(n.label));
        }

        // copy neighbors(edges)
        for (UndirectedGraphNode n : nodes) {
            UndirectedGraphNode newNode = mapping.get(n);
            for (UndirectedGraphNode neighbor : n.neighbors) {
                UndirectedGraphNode newNeighbor = mapping.get(neighbor);
                newNode.neighbors.add(newNeighbor);
            }
        }

        return mapping.get(node);
    }

    private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node) {
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        HashSet<UndirectedGraphNode> set = new HashSet<>();

        queue.offer(node);
        set.add(node);
        while (!queue.isEmpty()) {
            UndirectedGraphNode head = queue.poll();
            for (UndirectedGraphNode neighbor : head.neighbors) {
                if (!set.contains(neighbor)) {
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
        }

        return new ArrayList<UndirectedGraphNode>(set);
    }
}

更多题解参考:九章官网solution

相关文章
|
4月前
|
算法 搜索推荐 图计算
图计算中的社区发现算法是什么?请解释其作用和常用算法。
图计算中的社区发现算法是什么?请解释其作用和常用算法。
33 0
|
5月前
|
存储 算法 测试技术
☆打卡算法☆LeetCode 133. 克隆图 算法解析
☆打卡算法☆LeetCode 133. 克隆图 算法解析
|
18天前
|
存储 算法
图的深度优先算法
图的深度优先算法
19 0
|
20天前
|
算法 数据可视化 大数据
圆堆图circle packing算法可视化分析电商平台网红零食销量采集数据
圆堆图circle packing算法可视化分析电商平台网红零食销量采集数据
|
4月前
|
算法 搜索推荐 数据挖掘
图计算中的图算法有哪些常见的类型?请举例说明每种类型的算法。
图计算中的图算法有哪些常见的类型?请举例说明每种类型的算法。
41 0
|
4月前
|
算法 搜索推荐 Java
图计算中的PageRank算法是什么?请解释其作用和计算原理。
图计算中的PageRank算法是什么?请解释其作用和计算原理。
26 0
|
4月前
|
算法 搜索推荐 Java
图计算中的图剪枝算法是什么?请解释其作用和常用方法。
图计算中的图剪枝算法是什么?请解释其作用和常用方法。
16 0
|
6月前
|
算法 数据挖掘 知识图谱
LINE算法复现 图表示学习 基于line 算法的节点分类 聚类显示 完整代码+数据
LINE算法复现 图表示学习 基于line 算法的节点分类 聚类显示 完整代码+数据
21 0
|
7月前
|
存储 算法 图计算
TuGraph Analytics图计算快速上手之弱联通分量算法
TuGraph Analytics是蚂蚁集团近期开源的分布式流式图计算,目前广泛应用在蚂蚁集团的金融、社交、风控等诸多领域。
|
7月前
|
算法
带你读《图解算法小抄》七、图(1)
带你读《图解算法小抄》七、图(1)
带你读《图解算法小抄》七、图(1)