5ms Easy Java DFS solution using HashMap


  • 0
    public class Solution {
        
        private UndirectedGraphNode helper(UndirectedGraphNode node, Map<Integer,UndirectedGraphNode> map) {
            if(node==null)
                return null;
            if(map.containsKey(node.label))
                return map.get(node.label);
            UndirectedGraphNode startNode = new UndirectedGraphNode(node.label);
            map.put(startNode.label,startNode);
            for(UndirectedGraphNode neighbor : node.neighbors)
                startNode.neighbors.add(helper(neighbor, map));
            return startNode;
        }
        
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            return helper(node, new HashMap<Integer,UndirectedGraphNode>());
        }
    }

Log in to reply
 

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