`

Clone Graph

阅读更多
之所以把这道题单独拿出来,是因为通过它我们可以了解到图的结构,以及如何处理,我们分别用递归,广搜和深搜来完成这道题。

Clone Graph
复制一个无向图,图中每个节点都有一个label和一个neighbors集合。

解决图的题,因为图中存在环,我们要判断哪些点已经访问过了,做上标记,以防止进入死循环。这里我们用哈希函数来判断一个顶点是否被访问过,如果没被访问过就加入到哈希表中。
首先我们通过广搜来完成它。广搜用到队列,代码如下:

/**
 * 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) {
        HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        if(node == null) return null;
        UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
        hm.put(node,copy);
        queue.offer(node);
        while(!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();
            for(UndirectedGraphNode neighbor : cur.neighbors) {
                if(!hm.containsKey(neighbor)) {
                    copy = new UndirectedGraphNode(neighbor.label);
                    hm.put(neighbor, copy);
                    queue.offer(neighbor);
                }
                hm.get(cur).neighbors.add(hm.get(neighbor));
            }
        }
        return hm.get(node);
    }
}


深度搜索用到堆栈,代码如下:
/**
 * 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) {
        HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        Stack<UndirectedGraphNode> stack = new Stack<UndirectedGraphNode>();
        if(node == null) return null;
        stack.push(node);
        UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
        hm.put(node,copy);
        while(!stack.isEmpty()) {
            UndirectedGraphNode cur = stack.pop();
            for(UndirectedGraphNode neighbor : cur.neighbors) {
                if(!hm.containsKey(neighbor)) {
                    copy = new UndirectedGraphNode(neighbor.label);
                    hm.put(neighbor, copy);
                    stack.push(neighbor);
                }
                hm.get(cur).neighbors.add(hm.get(neighbor));
            }
        }
        return hm.get(node);
    }
}


递归实现:
/**
 * 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) {
        HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        return DFS(hm, node);
    }
    private UndirectedGraphNode DFS(HashMap<UndirectedGraphNode, UndirectedGraphNode> hm, UndirectedGraphNode node) {
        if(node == null) return null;
        UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
        hm.put(node, copy);
        for(UndirectedGraphNode neighbor : node.neighbors) {
            if(!hm.containsKey(neighbor)) {
                UndirectedGraphNode neighborcopy = DFS(hm, neighbor);
            }
            copy.neighbors.add(hm.get(neighbor));
        }
        return copy;
    }
}
分享到:
评论

相关推荐

    CloneGraph

    leetcode CloneGraph java 源代码

    【Lintcode】137. Clone Graph

    https://www.lintcode.com/problem/clone-graph/description Deep copy一个图。图以邻接表方式存储。 思路是,先从给定的顶点出发,搜索到图中的所有的顶点,然后为每个顶点创建一份拷贝;接着,遍历原图的顶点,每...

    133.Clone Graph 克隆图【LeetCode单题讲解系列】

    133.Clone_Graph_克隆图【LeetCode单题讲解系列】

    python-leetcode题解之133-Clone-Graph

    python python_leetcode题解之133_Clone_Graph

    js-leetcode题解之133-clone-graph.js

    javascript js_leetcode题解之133-clone-graph.js

    克隆图(python map+dfs)1

    `cloneGraph`函数的目的是接收一个`Node`对象并返回一个新的、完全独立的`Node`对象,所有节点及其连接关系都要被正确地复制。 解决方案是使用深度优先搜索策略。首先,创建一个空的`map_list`字典,用于存储原图中...

    leetcode java

    杂项部分包括了一些不那么容易归类的问题,如螺旋矩阵(Spiral Matrix)、整数转罗马数字(Integer to Roman)、克隆图(Clone Graph)等。 **栈(Stack)** 栈是一种先进后出(FILO)的数据结构。 - 最小栈(Min ...

    常见算法题答案及解析

    38. Clone Graph:复制一个无向图。 39. Min Stack:设计一个栈,支持获取栈内最小元素的操作。 40. Evaluate Reverse Polish Notation:计算后缀表达式的值。 41. Valid Parentheses:判断字符串是否为有效的括号...

    Leetcode book刷题必备

    38. Clone Graph:深度复制一个图。 【栈】 39. Min Stack:设计一个栈,支持 push、pop、top 操作,并且在常数时间内得到栈的最小值。 40. Evaluate Reverse Polish Notation:计算后缀表达式。 41. Valid ...

    lintcode题解

    - **CloneGraph(克隆图)**:复制一个图,要求每个节点只复制一次。 - **NQueens(N皇后问题)**:在一个N×N的棋盘上放置N个皇后,要求不相互攻击。 - **SixDegrees(六度空间理论)**:找出两个人之间的联系路径...

    Leetcode答案(c++版)

    **1.19 Clone Graph (133)** - **问题描述**:给定一个无向图,对其进行深拷贝。 - **解题思路**: - 使用深度优先搜索(DFS)或广度优先搜索(BFS)遍历整个图。 - 对于每个访问过的节点,创建一个副本,并将...

    algorithms:只是个菜鸟。这个项目是在空闲时间编写的。我会不定期更新。希望与您分享一些东西〜

    与大家分享我学习算法的一些经历。这个项目不定期更新。数组/链表:树相关:AVLTree 平衡二叉搜索树...BFSGraph 图BFS模板Dijkstra 寻求最短路SwimmingCrossSea 漂洋过海CloneGraph (leetcode 133)字符串相关:Reve

    leetcode同类骰子-Algorithms:LeetCode,GeeksforGeeks

    Clone Graph, medium --- 类似于#138 207,课程表,中等 210 课程表 II,中等 261,图有效树,中等 310,最小高度树,中等 323,无向图中连通分量的数量,中等 444,序列重建,中 第二周——堆 215,数组中的第 K 个...

    MapReduce-based Assembly Clone Search for Reverse Engineering.pdf

    We propose a new variant of LSH scheme and incorporate it with graph matching to address these challenges. We implement an integrated assembly clone search engine called Kam1n0. It is the first clone...

    Android代码-simplegraph

    If you clone the whole project, main app is a sample app that you can run and see simplegraph functionality in action. Why this library is out there? Well, I've spent too much time looking for library...

    LeetCode

    例如,"Clone Graph"题目中,通过DFS克隆一个无向图;"Shortest Path in Binary Matrix"则需要BFS寻找矩阵中最短路径。 总结,通过LeetCode的实践,我们可以提升JavaScript编程技巧,熟练掌握各种数据结构和算法,...

    ldbc_snb_janusgraph:LDBC SNB在Janusgraph上| 非常感谢我的队友!

    LDBC SNB在Janusgraph上... 解压缩 在配置了后端存储的情况下运行Janusgraph,请参阅bin/janusgraph start|status|stop|clean# bin/gremlin-server.sh #need configure backend storage克隆并构建git clone git@github....

    callgraph-gen:从 elf 二进制文件生成调用图

    $ sudo apt install libpcre2-dev libxml2-dev签出存储库并初始化所有子模块 $ git clone https://github.com/kuopinghsu/callgraph-gen.git$ cd callgraph-gen$ git submodule update --init --recursive建造 $ ...

    pose-graph-optimization:使用Ceres Solver进行2D姿态图优化

    依存关系本征3.3或更高版本Ceres Solver 1.12.0或更高版本Gflags 2.2.0或更高版本带有matplotlib的Python建造$ git clone https://github.com/shinsumicco/pose-graph-optimization.git$ cd pose-graph-optimization...

Global site tag (gtag.js) - Google Analytics