clone graph - Teeeeeebag/LeetCode GitHub Wiki
- Pay attention to the place where you update the hash map
public class Solution {
private HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null){
return null;
}
if (hm.containsKey(node)){
return hm.get(node);
}
hm.put(node, n); // The place of this statement is important
// Initially, I put it before return, it will run into infinite loop!
UndirectedGraphNode n = new UndirectedGraphNode(node.label);
for (UndirectedGraphNode crt : node.neighbors){
n.neighbors.add(cloneGraph(crt));
}
return n;
}
}