Created
November 12, 2017 06:13
-
-
Save shailrshah/4c22a6f342b911790fb3190dc92b7050 to your computer and use it in GitHub Desktop.
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
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
Map<Integer, UndirectedGraphNode> map = new HashMap<>(); | |
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { | |
if(node == null) return null; | |
if(map.containsKey(node.label)) | |
return map.get(node.label); | |
UndirectedGraphNode clonedNode = new UndirectedGraphNode(node.label); | |
map.put(clonedNode.label, clonedNode); | |
for(UndirectedGraphNode neighbor : node.neighbors) | |
clonedNode.neighbors.add(cloneGraph(neighbor)); | |
return clonedNode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment