5ms Java Solution


  • 2
    L
    public class Solution {
    final Map<Integer, UndirectedGraphNode> seen = new HashMap<Integer, UndirectedGraphNode>();
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
        dfs(copy, node);
        return copy;
    }
    private void dfs(UndirectedGraphNode copy, UndirectedGraphNode node){
        seen.put(node.label, copy);
        for(UndirectedGraphNode n:node.neighbors){
            if(!seen.containsKey(n.label)){
                UndirectedGraphNode newCopy = new UndirectedGraphNode(n.label);
                dfs(newCopy, n);
                copy.neighbors.add(newCopy);
            }
            else{
                copy.neighbors.add(seen.get(n.label));
            }
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.