标签:des style blog color strong for
Problem Description:
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
Solution:
1 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 2 if (node == null) { 3 return null; 4 } 5 Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); 6 Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); 7 queue.add(node); 8 while (!queue.isEmpty()) { 9 UndirectedGraphNode q = queue.poll(); 10 UndirectedGraphNode newNode = new UndirectedGraphNode(q.label); 11 map.put(q, newNode); 12 for (UndirectedGraphNode neighbor : q.neighbors) { 13 if (!map.containsKey(neighbor)) { 14 queue.add(neighbor); 15 } 16 } 17 } 18 Set<UndirectedGraphNode> keySet = map.keySet(); 19 for (UndirectedGraphNode p : keySet) { 20 UndirectedGraphNode n = map.get(p); 21 for (UndirectedGraphNode q : p.neighbors) { 22 n.neighbors.add(map.get(q)); 23 } 24 } 25 26 return map.get(node); 27 }
Problem Clone Graph,布布扣,bubuko.com
标签:des style blog color strong for
原文地址:http://www.cnblogs.com/liew/p/3815090.html