leetcode 133. Clone Graph 图遍历BFS + 避免循环

喜欢ヅ旅行 2022-06-08 05:57 281阅读 0赞

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ’s undirected graph serialization:
Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:

  1. 1
  2. / \
  3. / \
  4. 0 --- 2
  5. / \
  6. \_/

这道题考查的是图的遍历,可以使用BFS或者DFS,不过要避免循环。

代码如下:

  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Queue;
  7. /*class UndirectedGraphNode
  8. {
  9. int label;
  10. List<UndirectedGraphNode> neighbors;
  11. UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
  12. };
  13. */
  14. /*
  15. * 这个题主要的注意就是使用map映射结点信息
  16. * */
  17. public class Solution
  18. {
  19. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node)
  20. {
  21. if(node==null)
  22. return null;
  23. UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
  24. Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
  25. map.put(node, newNode);
  26. Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
  27. queue.add(node);
  28. while(queue.isEmpty()==false)
  29. {
  30. UndirectedGraphNode top = queue.poll();
  31. List<UndirectedGraphNode> list = top.neighbors;
  32. for(int i=0;i<list.size();i++)
  33. {
  34. UndirectedGraphNode one = list.get(i);
  35. if(map.containsKey(one)==false)
  36. {
  37. UndirectedGraphNode tmp = new UndirectedGraphNode(one.label);
  38. map.put(one, tmp);
  39. //只有新建的需要加入queue,否者不需要,避免图中的环
  40. queue.add(one);
  41. }
  42. map.get(top).neighbors.add(map.get(one));
  43. }
  44. }
  45. return newNode;
  46. }
  47. }

发表评论

表情:
评论列表 (有 0 条评论,281人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode133. Clone Graph

    133. Clone Graph ![这里写图片描述][SouthEast] 这道题目的意思是:对一个无向图进行深拷贝,即需要申请一个新的空间,并将原来的无向图中的节点