DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on • Originally published at rakeshpeddamallu.netlify.app

Leetcode - 133. Clone 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) {
  if (!node) return null;
let visited = new Map();
    const dfs = (original) =>{
    if (!original) return null;
        if(visited.has(original.val)){
            return visited.get(original.val)
        }else{
            const copy = new Node(original.val,[]);
            visited.set(copy.val, copy);
            original?.neighbors.forEach((nei)=>{
                copy.neighbors.push(dfs(nei));
            })
            return copy
        }
    }

    return dfs(node)
};
Enter fullscreen mode Exit fullscreen mode

Please do follow the series if you are struggling with leetcode questions šŸ˜‡

Top comments (0)