不要被题的样子吓到 只是很简单的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;
}
}

本文介绍了一种使用递归方法实现图复制的算法,并通过哈希映射确保节点的一致性和唯一性。该算法能有效避免重复创建相同的节点,提高图复制效率。
233

被折叠的 条评论
为什么被折叠?



