[关闭]
@w1024020103 2017-07-07T19:55:36.000000Z 字数 1431 阅读 493

Clone Graph

LintCode LeetCode


image_1bkea5vdh1mc01nuk19qrjos1l0j9.png-126.3kB

image_1bkea6og41sji19b92uhpqfht0m.png-64.4kB

这道题让克隆一个无向图,题目里关于如何序列化一个无向图的介绍对解题没有什么帮助。这道题仍然用BFS来解决,这个视频帮到我很多。

Clone Graph

基本思路是,1、先克隆所有的点;2、再克隆所有的联结关系。
用一个HashMap来形成原图和克隆图的mapping,同时可以用来保存已经被visited的节点。HashMap的key是original node, value 是clone node. 同时,每逢bfs几乎必用的Queue用来辅助遍历。注意,每次要将某些节点offer进queue等待下一步遍历的时候,也要将这些节点加入到HashMap里表示已经visited.但是,注意一开始加入到HashMap里的时候,value先设为null,直到poll这个节点出来遍历该点的时候,再将mapping更新为key = original node; value = clone node. (为什么先设为null呢?)

当所有的点都被克隆完后,还需要克隆初原来图中的连结关系。我们需要遍历出original graph的每个点的每个neighbor, 然后在clone graph里边先get到对应的点,再在这个点的neighbors里边add所有的neighbor.

  1. public class Solution {
  2. /**
  3. * @param node: A undirected graph node
  4. * @return: A undirected graph node
  5. */
  6. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node){
  7. if (node == null) {
  8. return null;
  9. }
  10. Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
  11. HashMap<UndirectedGraphNode,UndirectedGraphNode> visited = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
  12. queue.offer(node);
  13. visited.add(node, null);
  14. while (!queue.isEmpty()){
  15. UndirectedGraphNode temp = queue.poll();
  16. UndirectedGraphNode copy = new UndirectedGraphNode(temp.label);
  17. visited.put(temp, copy);
  18. for (UndirectedGraphNode neighbor : temp.neighbors){
  19. if (!visited.containsKey(neighbor)){
  20. queue.offer(neighbor);
  21. visited.put(neighbor, null);
  22. }
  23. }
  24. }
  25. for (UndirectedGraphNode original : visited.keySet()){
  26. UndirectedGraphNode cpy = visited.get(original);
  27. for (UndirectedGraphNode neighbor: original.neighbors){
  28. cpy.neighbors.add(visited.get(neighbor));
  29. }
  30. }
  31. return visited.get(node);
  32. }
  33. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注