关闭

Clone Graph

70人阅读 评论(0) 收藏 举报
分类:

updated: 06/10, 我们必须深刻理解什么是clone,不要将引用克隆

curNodeClone.neighbors.add(curNodeNeighborClone);
加入的是clone,而不是现有的引用

典型的bfs遍历问题,基本功

很棒的代码点击打开链接

/**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return null;
        }
        // 放原始node和其复制品  
        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        // BFS用的queue
        List<UndirectedGraphNode> list = new LinkedList<UndirectedGraphNode>(); 
        // 根节点的复制
        UndirectedGraphNode nodeClone = new UndirectedGraphNode(node.label);
        // 把根节点和其复制品放入map 
        map.put(node, nodeClone);
        //添加入队列  
        list.add(node);
        while (!list.isEmpty()) {
            // 当前处理对象
            UndirectedGraphNode curNode = list.remove(0);
            // 得到当前原始对象的所有neighbor  
            ArrayList<UndirectedGraphNode> curNodeNeighbors = curNode.neighbors;
            // 当前处理对象的复制品,必定在map里,因为在前面的neighbor里已经被创建
            UndirectedGraphNode curNodeClone = map.get(curNode);
            for (UndirectedGraphNode curNodeNeighbor: curNodeNeighbors) {
                if (map.containsKey(curNodeNeighbor)) {
                    //UndirectedGraphNode curNodeClone = map.get(curNode);
                    // 之前已经被复制过的neighbor
                    UndirectedGraphNode curNodeNeighborClone = map.get(curNodeNeighbor);
                    // 就直接从map里取出neighborClone, 给curClone添加复制的neighbor
                    curNodeClone.neighbors.add(curNodeNeighborClone);
                } else {
                    // 如果该neighbor没有被复制过,则新建neighborClone
                    UndirectedGraphNode curNodeNeighborClone = new UndirectedGraphNode(curNodeNeighbor.label);
                    //UndirectedGraphNode curNodeClone = map.get(curNode);
                    curNodeClone.neighbors.add(curNodeNeighborClone);
                    // 并且添加到队列里为了将来的遍历
                    list.add(curNodeNeighbor);
                    // 存储到map里
                    map.put(curNodeNeighbor, curNodeNeighborClone);
                }
            }
        }
        return nodeClone;
    }



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62159次
    • 积分:8099
    • 等级:
    • 排名:第2476名
    • 原创:795篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类