首页 > 代码库 > 133. Clone Graph

133. 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
         /          \_/

链接: http://leetcode.com/problems/clone-graph/

5/14/2017

14ms, 9%

用BFS的方法,先建立每个元素的copy,然后如果neighbor没有建立copy,把neighbor也放在queue当中。第二部分就是链接各个节点。

还要注意iterate through hashmap

 1 /**
 2  * Definition for undirected graph.
 3  * class UndirectedGraphNode {
 4  *     int label;
 5  *     List<UndirectedGraphNode> neighbors;
 6  *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 7  * };
 8  */
 9 public class Solution {
10     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
11         if (node == null) return null;
12         
13         Map<UndirectedGraphNode, UndirectedGraphNode> graphMap = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
14         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
15         
16         queue.offer(node);
17         // create copy of new nodes
18         while (!queue.isEmpty()) {
19             UndirectedGraphNode n = queue.poll();
20             if (!graphMap.containsKey(n)) {
21                 UndirectedGraphNode copy = new UndirectedGraphNode(n.label);
22                 graphMap.put(n, copy);
23             }
24             for (UndirectedGraphNode neighbor: n.neighbors) {
25                 if (!graphMap.containsKey(neighbor)) {
26                     queue.offer(neighbor);
27                 }
28             }
29         }
30         // build neighbors
31         for (Map.Entry<UndirectedGraphNode, UndirectedGraphNode> entry: graphMap.entrySet()) {
32             UndirectedGraphNode original = entry.getKey();
33             UndirectedGraphNode copy = entry.getValue();
34             for (UndirectedGraphNode neighbor: original.neighbors) {
35                 copy.neighbors.add(graphMap.get(neighbor));
36             }
37         }
38         return graphMap.get(node);
39     }
40 }

也可以在copy的时候直接建立neighbors

https://discuss.leetcode.com/topic/4690/simple-java-iterative-bfs-solution-with-hashmap-and-queue

DFS做法

https://discuss.leetcode.com/topic/9629/depth-first-simple-java-solution

更多讨论

https://discuss.leetcode.com/category/141/clone-graph

133. Clone Graph