Consise and easy to understand Java Solution


  • 4
    I

    public class Solution {

    HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
    
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
        map.put(node, copy);
        
        for(UndirectedGraphNode x : node.neighbors){
            if(map.get(x) == null){
                copy.neighbors.add(cloneGraph(x));
            }else{
                copy.neighbors.add(map.get(x));
            }
        }
        return copy;
    }
    

    }


  • 0
    R

    Very easy to code solution. I implemented it in python.


Log in to reply
 

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