zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    Dreamweaver中SourceAnyWhere的使用
    访问被拒绝:“AjaxPro”的解决方案
    NDoc1.3.1使用手册
    程序中操作Excel
    模拟提交程序相关专题
    利用SMTP服务发送电子邮件
    如何使用树形控件
    GDI+简单使用例子
    程序中操作Word
    签名工具使用介绍
  • 原文地址:https://www.cnblogs.com/gonuts/p/4391970.html
Copyright © 2011-2022 走看看