DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Clone graph

O(n) : where n is no. of nodes
Problem

/*
Definition for a Node.
class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}
*/

class Solution {
    public Node cloneGraph(Node node) {
        if(node ==null) return null;
        Map<Node,Node> map = new HashMap<>();
        Node cloneNode = new Node(node.val);
        return dfs(node,cloneNode,map);
    }

    public Node dfs(Node a, Node b,Map<Node,Node> map){
        if(map.containsKey(a)) return map.get(a);
        map.put(a,b);
        for(Node adjNode : a.neighbors){
            if(!map.containsKey(adjNode)){
                Node newNode = new Node(adjNode.val);
                b.neighbors.add(dfs(adjNode,newNode,map));
            }
            else{
                b.neighbors.add(map.get(adjNode));
            } 
        }
        return b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌶️ Newest Episode of Leet Heat: A Game Show For Developers!

Contestants face rapid-fire full stack web dev questions. Wrong answers? The spice level goes up. Can they keep cool while eating progressively hotter sauces?

View Episode Post

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️