Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 18, 2016 03:38
Show Gist options
  • Save cangoal/d48850ef557cba92676b to your computer and use it in GitHub Desktop.
Save cangoal/d48850ef557cba92676b to your computer and use it in GitHub Desktop.
LeetCode - Clone Graph
//DFS
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
return helper(node, map);
}
private UndirectedGraphNode helper(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map){
if(node == null) return node;
if(map.containsKey(node)) return map.get(node);
UndirectedGraphNode copyNode = new UndirectedGraphNode(node.label);
map.put(node, copyNode);
for(UndirectedGraphNode nbnode : node.neighbors){
copyNode.neighbors.add(helper(nbnode, map));
}
return copyNode;
}
// Another version of DFS
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return node;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
UndirectedGraphNode copyNode = new UndirectedGraphNode(node.label);
map.put(node, copyNode);
helper(node, map);
return map.get(node);
}
private void helper(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map){
if(node == null) return;
for(UndirectedGraphNode nbnode : node.neighbors){
if(!map.containsKey(nbnode)){
UndirectedGraphNode temp = new UndirectedGraphNode(nbnode.label);
map.put(nbnode, temp);
map.get(node).neighbors.add(temp);
helper(nbnode, map);
} else {
map.get(node).neighbors.add(map.get(nbnode));
}
}
}
// BFS
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
UndirectedGraphNode copyNode = new UndirectedGraphNode(node.label);
map.put(node, copyNode);
while(!queue.isEmpty()){
UndirectedGraphNode Node = queue.poll();
copyNode = map.get(Node);
for(UndirectedGraphNode neighbor : Node.neighbors){
if(!map.containsKey(neighbor)){
UndirectedGraphNode copyNeighbor = new UndirectedGraphNode(neighbor.label);
copyNode.neighbors.add(copyNeighbor);
map.put(neighbor, copyNeighbor);
queue.offer(neighbor);
}else{
copyNode.neighbors.add(map.get(neighbor)); //
}
}
}
return map.get(node);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment