码迷,mamicode.com
首页 > 其他好文 > 详细

Problem Clone Graph

时间:2014-07-07 16:11:57      阅读:192      评论:0      收藏:0      [点我收藏+]

标签: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

Problem Clone Graph

标签:des   style   blog   color   strong   for   

原文地址:http://www.cnblogs.com/liew/p/3815090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!