Short and Simple java DFS solution.


  • 0
    A
    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        Map<UndirectedGraphNode,UndirectedGraphNode> hm = new HashMap <UndirectedGraphNode,UndirectedGraphNode>();
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null){
                return null;
            }
            if (!hm.containsKey (node)){
                hm.put (node,new UndirectedGraphNode (node.label));
                for (UndirectedGraphNode ugn : node.neighbors){
                    hm.get(node).neighbors.add (cloneGraph (ugn));
                }
            }
            return hm.get (node);
        }
    }

Log in to reply
 

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