思路:首先遍历所有的元素,添加到map中,然后读取map,给每个元素编号,放进list中,同时新建list存储每个复制了lable的元素。最后读取原list,查看该list每个邻居,去map中查看这些邻居的编号,去新list中找到对应的邻居,添加到对应的元素的邻居中。
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node!=null) {
Map<UndirectedGraphNode, Integer> initMap=f(node,new HashMap<UndirectedGraphNode, Integer>());
Map<UndirectedGraphNode, Integer> map=new HashMap<UndirectedGraphNode, Integer>();
map.put(node, 0);
List<UndirectedGraphNode> list=new ArrayList<UndirectedGraphNode>();
list.add(node);
List<UndirectedGraphNode> ans=new ArrayList<UndirectedGraphNode>();
UndirectedGraphNode init=new UndirectedGraphNode(node.label);
ans.add(init);
int k=1;
for (UndirectedGraphNode ugn : initMap.keySet()) {
if (ugn!=node) {
map.put(ugn, k);
list.add(ugn);
ans.add(new UndirectedGraphNode(ugn.label));
k++;
}
}
for (int i = 0; i < list.size(); i++) {
List<UndirectedGraphNode> neis=list.get(i).neighbors;
UndirectedGraphNode u=ans.get(i);
for (int j = 0; j < neis.size(); j++) {
u.neighbors.add(ans.get(map.get(neis.get(j))));
}
}
return init;
}
return null;
}
public Map<UndirectedGraphNode, Integer> f(UndirectedGraphNode node,Map<UndirectedGraphNode, Integer> map){
if (node!=null&&map.get(node)==null) {
map.put(node, 1);
List<UndirectedGraphNode> list=node.neighbors;
if (list!=null) {
for (int i = 0; i < list.size(); i++) {
map=f(list.get(i),map);
}
}
}
return map;
}
}
本文介绍了一种基于图的深拷贝算法实现方法。通过使用Map存储已访问的节点并给每个节点进行唯一编号,文章详细展示了如何构建新的图结构,并通过遍历原图的每个节点及其邻居来建立新图的连接关系。
272

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



