Clone Graph

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

OJ's undirected graph serialization:

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:

       1
      / \
     /   \
    0 --- 2
         / \
         \_/

思路:1.clone nodes 2. clone nodes's neighbors 3. 利用HashMap 记录 旧节点 与 新clone节点的映射关系。
相关题目:copy random LinkedList
 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             return null;
17         }
18         ArrayList<UndirectedGraphNode> nodes = new ArrayList<>();
19         HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
20         nodes.add(node);
21         map.put(node, new UndirectedGraphNode(node.label));
22         int start = 0;
23         while (start < nodes.size()) {
24             UndirectedGraphNode head = nodes.get(start++);
25             for (int i = 0; i < head.neighbors.size(); i++) {
26                 UndirectedGraphNode neighbor = head.neighbors.get(i);
27                 if (!map.containsKey(neighbor)) {
28                     map.put(neighbor, new UndirectedGraphNode(neighbor.label));
29                     nodes.add(neighbor);
30                 }
31             }
32         }
33 
34         for (int i = 0; i < nodes.size(); i++) {
35             UndirectedGraphNode newNode = map.get(nodes.get(i));
36                for (int j = 0; j < nodes.get(i).neighbors.size(); j++) {
37                    newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j)));
38             }
39         }
40         return map.get(node);
41     }
42 }

 

posted @ 2016-04-29 15:22  YuriFLAG  阅读(189)  评论(0)    收藏  举报