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])
            }
        }
    }
  • 相关阅读:
    grunt in webstorm
    10+ Best Responsive HTML5 AngularJS Templates
    响应式布局
    responsive grid
    responsive layout
    js event bubble and capturing
    Understanding Service Types
    To add private variable to this Javascript literal object
    Centering HTML elements larger than their parents
    java5 新特性
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10946691.html
Copyright © 2011-2022 走看看