zoukankan      html  css  js  c++  java
  • 133. Clone Graph(js)

    133. Clone Graph

    Given a reference of a node in a connected undirected graph, return a deep copy(clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

    Example:

    Input:
    {"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
    
    Explanation:
    Node 1's value is 1, and it has two neighbors: Node 2 and 4.
    Node 2's value is 2, and it has two neighbors: Node 1 and 3.
    Node 3's value is 3, and it has two neighbors: Node 2 and 4.
    Node 4's value is 4, and it has two neighbors: Node 1 and 3.
    题意:深克隆图
    代码如下:
    /**
     * // Definition for a Node.
     * function Node(val,neighbors) {
     *    this.val = val;
     *    this.neighbors = neighbors;
     * };
     */
    /**
     * @param {Node} node
     * @return {Node}
     */
    var cloneGraph = function(node) {
        if (!node) return node;
        
        const ref = {};
        const copy = new Node(node.val, []);
        
        ref[node.val] = copy;
        dfs(node, ref);
        return copy;
    };
    
    var dfs = function(node, ref) {
        for (let neighbor of node.neighbors) {
            if (!ref[neighbor.val]) {
                const copy = new Node(neighbor.val, []);
                ref[neighbor.val] = copy;
                ref[node.val].neighbors.push(copy);
                dfs(neighbor, ref)
            } else {
                ref[node.val].neighbors.push(ref[neighbor.val])
            }
        }
    }
  • 相关阅读:
    Mac下django简单安装配置步骤
    NuGet 使用笔记
    gulp es7配置文件
    HaProxy配置
    Java工作环境笔记
    ReactJs笔记
    架构应该解决好对象的克隆问题
    Kotlin笔记
    Scala 笔记
    spark 笔记
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10946691.html
Copyright © 2011-2022 走看看