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);
}
}