• Clone Graph


    这题第一眼看到想到的是BFS。接着想到我需要一个queue来做BFS。之后,为了能一一对应的复制,还用到一个Map。对应新旧node。

    BUG: 就是我在复制新child node之前,就把旧child node添加到新的node的neighbors中了。

     1     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
     2         if (node == null) {
     3             return null;
     4         }
     5         Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
     6         Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
     7         UndirectedGraphNode nodeCopy = new UndirectedGraphNode(node.label);
     8         q.add(node);
     9         map.put(node, nodeCopy);
    10         while (!q.isEmpty()) {
    11             UndirectedGraphNode cur = q.poll();
    12             UndirectedGraphNode curCopy = map.get(cur);
    13             for (UndirectedGraphNode child : cur.neighbors) {
    14                 if (!map.containsKey(child)) {
    15                     UndirectedGraphNode childCopy = new UndirectedGraphNode(child.label);
    16                     map.put(child, childCopy);
    17                     q.offer(child);
    18                 }
    19                 //BUG:先复制child node
    20                 curCopy.neighbors.add(map.get(child));
    21             }
    22         }
    23         return map.get(node);
    24     }
  • 相关阅读:
    宜未雨而绸缪,毋临渴而掘井。
    JDBC fetch size
    社会主义核心价值观
    JavaEE
    《夜泊牛渚怀古》
    JAVA "GMT+10" 和 "GMT+0010"
    乡村振兴1
    申论 题好文一半
    UCOS时钟与中断:
    任务的状态-挂起和恢复
  • 原文地址:https://www.cnblogs.com/gonuts/p/4391970.html
Copyright © 2020-2023  润新知