Concise DFS Solution


  • 0
    public class Solution {
        private Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null) return null;
            dfs(node);
            return map.get(node);
        }
        private void dfs(UndirectedGraphNode node) {
            if (map.containsKey(node)) return;
            else map.put(node, new UndirectedGraphNode(node.label));
            for (int i = 0; i < node.neighbors.size(); i++) {
                dfs(node.neighbors.get(i));
                map.get(node).neighbors.add(map.get(node.neighbors.get(i)));
            }
        }
    }
    

Log in to reply
 

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