Cloning a graph


Cloning a graph is one of the easier problems. A quick code demonstrates this …

import java.util.*;

public class CloneGraph {
    public class Node{
        int val = 0;
        List neighbors = null;
        public Node(int val, List neighbors){
            this.val = val;
            this.neighbors = neighbors;
    public Node cloneGraph(Node node) {
        return duplicate(node);
    Map<Node, Node> visited = new HashMap();
    private Node duplicate(Node n){
        List<Node> dup_children = new ArrayList();
        Node dupl = new Node(n.val, dup_children);
            return visited.get(n);
            visited.put(n, dupl);
                dup_children = dupl.neighbors;
                for(Object child: n.neighbors){
                    Node dup_child = duplicate((Node)child);
        return dupl;

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.