Clone Graph Simple Java Solution


  • 0
    U
    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        private HashMap<Integer, UndirectedGraphNode> visitedNodeMap = new HashMap<>();
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null)
                return null;
            UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
            visitedNodeMap.put(clone.label, clone);
            for (UndirectedGraphNode neighbor : node.neighbors) {
                if (!visitedNodeMap.containsKey(neighbor.label))
                    clone.neighbors.add(cloneGraph(neighbor));
                else
                    clone.neighbors.add(visitedNodeMap.get(neighbor.label));
            }
            return clone;
        }
    }

Log in to reply
 

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