Created
July 7, 2021 18:46
-
-
Save saswata-dutta/0630c7d51c18b429279e389d882cbfc9 to your computer and use it in GitHub Desktop.
clone a graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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