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

133. Clone Graph

时间:2016-06-17 06:18:20      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

图的遍历,也就是bfs,区别在于,每一个点的左右节点不是预先知道的,是要创建的时候加进去

 

 1     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
 2         if(node == null) {
 3             return null;
 4         }
 5         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
 6         UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
 7         queue.offer(node);
 8         Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
 9         map.put(node, newNode);
10         while(!queue.isEmpty()) {
11             UndirectedGraphNode cur = queue.poll();
12             for(UndirectedGraphNode neighbor: cur.neighbors) {
13                 UndirectedGraphNode newNeighbor = map.get(neighbor);
14                 if(!map.containsKey(neighbor)) {
15                     newNeighbor = new UndirectedGraphNode(neighbor.label);
16                     map.put(neighbor, newNeighbor);
17                     queue.add(neighbor);
18                 }
19                 map.get(cur).neighbors.add(newNeighbor);
20             }
21         }
22         return newNode;
23     }

 

133. Clone Graph

标签:

原文地址:http://www.cnblogs.com/warmland/p/5592682.html

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