Simple dfs java solution


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

Log in to reply
 

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