Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Created July 7, 2021 18:46
Show Gist options
  • Save saswata-dutta/0630c7d51c18b429279e389d882cbfc9 to your computer and use it in GitHub Desktop.
Save saswata-dutta/0630c7d51c18b429279e389d882cbfc9 to your computer and use it in GitHub Desktop.
clone a graph
public class Solution {
private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
return clone(node);
}
private UndirectedGraphNode clone(UndirectedGraphNode node) {
if (node == null) return null;
if (map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
map.put(clone.label, clone);
for (UndirectedGraphNode neighbor : node.neighbors) {
clone.neighbors.add(clone(neighbor));
}
return clone;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment