0

I'm having some trouble understanding the bug in my code and why it's timing out. The problem is to create a clone of a directed graph. Here's a link to the question: https://www.educative.io/m/clone-directed-graph

My solution uses a queue twice. The first time I map all the nodes in the graph to what its corresponding node in the clone would be.

The second time I use to queue to iterate over the neighbours but get their corresponding mapped values and add those to the neighbours list for the current node I'm on.

Here's my code.

class Node {
  public int data;
  public List<Node> neighbors = new ArrayList<Node>();
  public Node(int d) {data = d;}
}

class graph {
  public static Node clone(Node root) {
    //use a queue to search the graph
    //use a haspmap to map graph node to clone node
    
    Queue<Node> q = new LinkedList<>();
    Map<Node, Node> map = new HashMap<>();
    q.add(root);
    map.put(root, new Node(root.data));

    while(!q.isEmpty()) {
      Node current = q.remove();
      
      for(Node temp : current.neighbors) {
        Node cloneTemp = new Node(temp.data);
        if(!map.containsKey(temp)) {
          q.add(temp);
          map.put(temp, cloneTemp);
        }
      }
    }
    q.add(root);
    while(!q.isEmpty()) {
      Node current = q.remove();
      Node currentClone = map.get(current);
        for(Node temp : current.neighbors) {
          Node mapNode = map.get(temp)
          if(!currentClone.neighbors.contains(mapNode)) {
            currentClone.neighbors.add(mapNode);
            q.add(temp);
          }
        }
      }
      
    return map.get(root);
  }
}
j.Doie
  • 91
  • 1
  • 6
  • 1
    What will happens in second `while` if you will have cycle in graph? Like node A pointing to node B and B pointing to A? You need to know which nodes was already visited and do not process them again. – tym32167 Sep 30 '20 at 02:09
  • @tym32167 that's right, thanks. I added that logic with an if statement it seems to be working now! – j.Doie Sep 30 '20 at 02:35

0 Answers0