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])
        }
    }
}

 

posted @ 2019-05-29 22:26  mingL  阅读(131)  评论(0编辑  收藏  举报