I was doing this problem clone a graph on leetcode but I’m getting “You must return a copy of all the nodes in the original graph” as the output.
it is said in the problem that the graph will not contain any self loop.
Here’s my code-
set<Node*> s;
Node* head=nullptr;
Node* dfs(Node* root, Node* prev, Node* copyofprevnode){
Node* newNode = new Node(root->val,{});
if(head==nullptr) head = newNode; // this line executes only once just to store the 1st node of cloned graph
s.insert(root);
if(copyofprevnode!=nullptr) newNode->neighbors.push_back(copyofprevnode);
for(auto x : root->neighbors){
if(x!=prev && s.count(x)==0) newNode->neighbors.push_back(dfs(x,root,newNode));
}
s.erase(root);
return newNode;
}
Node* cloneGraph(Node* node) {
dfs(node,nullptr,nullptr);
return head;
}
Can anybody help?