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 #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
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
/ \
\_/
Solution 1:
使用BFS来解决此问题。用一个Queue来记录遍历的节点,遍历原图,并且把复制过的节点与原节点放在MAP中防止重复访问。
图的遍历有两种方式,BFS和DFS
这里使用BFS来解本题,BFS需要使用queue来保存neighbors
但这里有个问题,在clone一个节点时我们需要clone它的neighbors,而邻居节点有的已经存在,有的未存在,如何进行区分?
这里我们使用Map来进行区分,Map的key值为原来的node,value为新clone的node,当发现一个node未在map中时说明这个node还未被clone,
将它clone后放入queue中处理neighbors。
使用Map的主要意义在于充当BFS中Visited数组,它也可以去环问题,例如A--B有条边,当处理完A的邻居node,然后处理B节点邻居node时发现A已经处理过了
处理就结束,不会出现死循环。
queue中放置的节点都是未处理neighbors的节点。
http://www.cnblogs.com/feiling/p/3351921.html
1 /* 2 Iteration Solution: 3 */ 4 public UndirectedGraphNode cloneGraph1(UndirectedGraphNode node) { 5 if (node == null) { 6 return null; 7 } 8 9 UndirectedGraphNode root = null; 10 11 // store the nodes which are cloned. 12 HashMap<UndirectedGraphNode, UndirectedGraphNode> map = 13 new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); 14 15 Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>(); 16 17 q.offer(node); 18 UndirectedGraphNode rootCopy = new UndirectedGraphNode(node.label); 19 20 // 别忘记这一行啊。orz.. 21 map.put(node, rootCopy); 22 23 // BFS the graph. 24 while (!q.isEmpty()) { 25 UndirectedGraphNode cur = q.poll(); 26 UndirectedGraphNode curCopy = map.get(cur); 27 28 // bfs all the childern node. 29 for (UndirectedGraphNode child: cur.neighbors) { 30 // the node has already been copied. Just connect it and don't need to copy. 31 if (map.containsKey(child)) { 32 curCopy.neighbors.add(map.get(child)); 33 continue; 34 } 35 36 // put all the children into the queue. 37 q.offer(child); 38 39 // create a new child and add it to the parent. 40 UndirectedGraphNode childCopy = new UndirectedGraphNode(child.label); 41 curCopy.neighbors.add(childCopy); 42 43 // Link the new node to the old map. 44 map.put(child, childCopy); 45 } 46 } 47 48 return rootCopy; 49 }