[LintCode] Clone Graph

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

以上是关于[LintCode] Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Clone Graph

[LintCode] Graph Valid Tree

[LeetCode]题解(python):133-Clone Graph

[LintCode] Connecting Graph

[LintCode] Graph Valid Tree

[LintCode] Connecting Graph III