C
Join ServerC#
help
LeetCode - Clone Graph [Answered]
BBen8/29/2022
Hey, trying to solve - https://leetcode.com/problems/clone-graph/
basically - question is to deep-clone a graph.
Could anyone helped me figure out why my solution isn't valid?
Error message -
My code -
basically - question is to deep-clone a graph.
Could anyone helped me figure out why my solution isn't valid?
Error message -
You must return a copy of all the nodes in the original graph
My code -
public Node CloneGraph(Node node)
{
var map = new Dictionary<int, Node>();
var clone = new Node(node.val);
dfs(node, clone, map);
return clone;
}
public void dfs(Node source, Node target, Dictionary<int, Node> map)
{
foreach(var sourceNeighbor in source.neighbors)
{
Node targetNeighbor;
if(!map.TryGetValue(sourceNeighbor.val, out targetNeighbor))
{
targetNeighbor = new Node(sourceNeighbor.val);
map.Add(targetNeighbor.val, targetNeighbor);
dfs(sourceNeighbor, targetNeighbor, map);
}
target.neighbors.Add(targetNeighbor);
}
}
PPobiega8/29/2022
have you made unittests?
PPobiega8/29/2022
so you can test it with a few known graphs
BBen8/29/2022
fml... found the issue.
I needed to add the initial
I needed to add the initial
clone
variable to the hashmap before going into the dfs logic.BBen8/29/2022
I'll close this, thanks Pobiega
AAccord8/29/2022
✅ This post has been marked as answered!