不要被题的样子吓到 只是很简单的recursive 但是记得node要存在hashmap里面 已经建立过的node就不要再建一遍了
public class Solution {
private HashMap <Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if ( node == null )
return null;
int label = node.label;
if ( map.containsKey( label ) )
return map.get(label);
UndirectedGraphNode res = new UndirectedGraphNode( label );
map.put( label, res );
for ( UndirectedGraphNode nei : node.neighbors ){
UndirectedGraphNode neighbor = cloneGraph( nei );
res.neighbors.add( neighbor );
}
return res;
}
}