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
时间: 2024-10-11 22:28:27