Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
[解题思路]
图的遍历有两种方式,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的节点!!!!
1 /** 2 * Definition for undirected graph. 3 * class UndirectedGraphNode { 4 * int label; 5 * ArrayListneighbors; 6 * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList (); } 7 * }; 8 */ 9 public class Solution {10 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {11 // Note: The Solution object is instantiated only once and is reused by each test case.12 if(node == null){13 return node;14 }15 UndirectedGraphNode result = new UndirectedGraphNode(node.label);16 LinkedList queue = new LinkedList ();17 queue.add(node);18 Map map = new HashMap ();19 map.put(node, result);20 21 while(!queue.isEmpty()){22 UndirectedGraphNode nodeInQueue = queue.poll();23 ArrayList neighbors = nodeInQueue.neighbors;24 for(int i = 0; i < neighbors.size(); i++){25 UndirectedGraphNode n1 = neighbors.get(i);26 if(map.containsKey(n1)){27 map.get(nodeInQueue).neighbors.add(map.get(n1));28 } else {29 UndirectedGraphNode n1clone = new UndirectedGraphNode(n1.label);30 map.get(nodeInQueue).neighbors.add(n1clone);31 map.put(n1, n1clone);32 queue.add(n1);33 }34 }35 36 }37 return result;38 }39 }
ref: