美文网首页
133. Clone Graph

133. Clone Graph

作者: jluemmmm | 来源:发表于2021-10-03 13:52 被阅读0次

    给无向连通图中节点的引用,返回图的深拷贝。

    DFS

    对访问过的节点进行标记,然后用dfs

    • 时间复杂度O(n),空间复杂度O(n)
    • Runtime: 103 ms, faster than 23.59%
    • Memory Usage: 39.7 MB, less than 95.77%
    /**
     * // Definition for a Node.
     * function Node(val, neighbors) {
     *    this.val = val === undefined ? 0 : val;
     *    this.neighbors = neighbors === undefined ? [] : neighbors;
     * };
     */
    
    /**
     * @param {Node} node
     * @return {Node}
     */
    const visited = new Map();
    var cloneGraph = function(node) {
      if (!node) {
        return node;
      }
      if (visited.has(node)) {
        return visited.get(node);
      }
      const cloneNode = new Node(node.val, []);
      visited.set(node,cloneNode);
      for (const i of node.neighbors) {
        cloneNode.neighbors.push(cloneGraph(i))
      }
      return cloneNode;
    };
    

    BFS

    这个解法有点问题,会返回 You must return a copy of all the nodes in the original graph,应该是哪里没有深复制的原因

    /**
     * // Definition for a Node.
     * function Node(val, neighbors) {
     *    this.val = val === undefined ? 0 : val;
     *    this.neighbors = neighbors === undefined ? [] : neighbors;
     * };
     */
    
    /**
     * @param {Node} node
     * @return {Node}
     */
    var cloneGraph = function(node) {
      const visited = new Map();
      const queue = [node];
      visited.set(node, new Node(node.val, []));
      while (queue.length > 0) {
        const n = queue.shift();
        for (const i of node.neighbors) {
          if(!visited.get(i)) {
            visited.set(i, new Node(i.val, []));
            queue.push(i);
          }
          visited.get(n).neighbors.push(visited.get(i));
        }
      }
      return visited.get(node);
    };
    

    相关文章

      网友评论

          本文标题:133. Clone Graph

          本文链接:https://www.haomeiwen.com/subject/mymvnltx.html