zoukankan      html  css  js  c++  java
  • [LintCode] Clone Graph

    Deep clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

    How we serialize an undirected graph:

    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 #.

    1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
    2. Second node is labeled as 1. Connect node 1 to node 2.
    3. 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:

    Algorithm:

    If we copy graph nodes as we do a bfs, there will be problems if the graph has self cycle. Also since the input graph is undirected, for each edge, we need to add it to both nodes.The regular bfs skips nodes that have already been visited, which makes adding an edge to both nodes' neighbors list difficult.

    A simpler solution is as follows. O(n + m) runtime, O(n) space

    1. bfs to get all original nodes.

    2. copy all nodes and create a mapping between the original nodes and copied nodes.

    3. Iterate the original nodes list from step 1 and construct the edges for the copied graph using the mapping relation from step 2.

     
     1 /**
     2  * Definition for undirected graph.
     3  * class UndirectedGraphNode {
     4  *     int label;
     5  *     ArrayList<UndirectedGraphNode> neighbors;
     6  *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     7  * };
     8  */
     9 public class Solution {
    10     /**
    11      * @param node: A undirected graph node
    12      * @return: A undirected graph node
    13      */
    14     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    15         if(node == null)
    16         {
    17             return null;
    18         }
    19         
    20         //use bfs algorithm to traverse the graph and get all nodes 
    21         ArrayList<UndirectedGraphNode> nodes = getNodes(node);
    22         HashMap<UndirectedGraphNode, UndirectedGraphNode> copyMapping = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
    23         //copy nodes
    24         for(UndirectedGraphNode n : nodes)
    25         {
    26             copyMapping.put(n, new UndirectedGraphNode(n.label));
    27         }
    28         
    29         //copy neighbors(edges)
    30         for(UndirectedGraphNode n : nodes)
    31         {
    32             UndirectedGraphNode newNode = copyMapping.get(n);
    33             for(UndirectedGraphNode neighbor : n.neighbors)
    34             {
    35                 UndirectedGraphNode newNeighbor = copyMapping.get(neighbor);
    36                 newNode.neighbors.add(newNeighbor);
    37             }
    38         }
    39         return copyMapping.get(node);
    40     }
    41     private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node)
    42     {
    43         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
    44         HashSet<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
    45         
    46         queue.offer(node);
    47         visited.add(node);
    48         while(!queue.isEmpty())
    49         {
    50             UndirectedGraphNode head = queue.poll();
    51             for(UndirectedGraphNode neighbor : head.neighbors)
    52             {
    53                 if(!visited.contains(neighbor))
    54                 {
    55                     visited.add(neighbor);
    56                     queue.offer(neighbor);
    57                 }
    58             }
    59         }
    60         return new ArrayList<UndirectedGraphNode>(visited);
    61     }
    62 }
     

    Related Problems

    Six Degrees

    Clone Binary Tree

    Route Between Two Nodes in Graph

  • 相关阅读:
    java基础(七) java四种访问权限
    java基础(六) switch语句的深入解析
    JavaSe: 不要小看了 Serializable
    对于培训出身的同学,接下来该怎么学习技术?
    Java Tomcat7性能监控与优化详解
    模仿spring-aop的功能,利用注解搭建自己的框架。
    动态页面技术EL
    如何在mysql客户端即mysql提示符下执行操作系统命令
    通过notepad++将混乱的xml配置的格式进行美化
    shell脚本中,for基于列表进行循环的实现方法
  • 原文地址:https://www.cnblogs.com/lz87/p/7496912.html
Copyright © 2011-2022 走看看