code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

04 Clone Graph

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val = 0, neighbors = []) {
  this.val = val
  this.neighbors = neighbors
}

const cloneGraph = node => {
  const map = new Map()
  const dfs = node => {
    if (map.has(node)) {
      return map.get(node)
    }
    const copy = new Node(node.val)
    map.set(node, copy)
    for (const neighbor of node.neighbors) {
      copy.neighbors.push(dfs(neighbor))
    }
    return copy
  }
  return dfs(node)
}

console.log(
  cloneGraph([
    [2, 4],
    [1, 3],
    [2, 4],
    [1, 3],
  ]),
)

Created 2022-02-13T06:01:45+00:00 · Edit