My accepted simple DFS java solution

  • 1

    map stores the visited nodes and corresponding clone node. If node is already visited, then nothing to do; otherwise, visit all the neighbors, and add cloned neighbors.

     public class Solution {
            public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
                if(node==null) return null;
                Map<UndirectedGraphNode, UndirectedGraphNode>  map = new HashMap<>();
                clone(node, map);
                return map.get(node);
            private void clone(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
                if(map.containsKey(node)) return;
                map.put(node, new UndirectedGraphNode(node.label));
                for(UndirectedGraphNode t : node.neighbors) {
                    clone(t, map);

Log in to reply

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