133. Clone Graph

图的遍历,也就是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     }

 

posted @ 2016-06-17 04:49  warmland  阅读(103)  评论(0编辑  收藏  举报