题目描述
https://oj.leetcode.com/problems/clone-graph/
思路
第一遍遍历图,在每个节点的neighbors列表的末尾加上一个selfCopyNode,即对该节点的复制节点。
第二遍遍历图,对每个节点的复制节点,让它的每个neighbor都是原节点对应neighbor复制节点。
第三遍遍历图,移除每个节点的selfCopyNode,还原原来的graph,否则无法AC。
代码
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)return node;
Queue<UndirectedGraphNode> q=new LinkedList<UndirectedGraphNode>();
Set<Integer> visit=new HashSet<Integer>();
visit.add(node.label);
q.offer(node);
while(!q.isEmpty()){
UndirectedGraphNode pNode=q.poll();
for(UndirectedGraphNode neighbor:pNode.neighbors){
if(!visit.contains(neighbor.label)){
q.offer(neighbor);
visit.add(neighbor.label);
}
}
UndirectedGraphNode selfCopyNode=new UndirectedGraphNode(pNode.label);
pNode.neighbors.add(selfCopyNode);
}
visit.clear();
visit.add(node.label);
q.offer(node);
while(!q.isEmpty()){
UndirectedGraphNode pNode=q.poll();
int size=pNode.neighbors.size();
UndirectedGraphNode selfCopyNode=pNode.neighbors.get(size-1);
for(int i=0;i<size-1;i++){
UndirectedGraphNode neighbor=pNode.neighbors.get(i);
if(!visit.contains(neighbor.label)){
q.offer(neighbor);
visit.add(neighbor.label);
}
selfCopyNode.neighbors.add(neighbor.neighbors.get(neighbor.neighbors.size()-1));
}
}
UndirectedGraphNode root=node.neighbors.get(node.neighbors.size()-1);
visit.clear();
visit.add(node.label);
q.offer(node);
while(!q.isEmpty()){
UndirectedGraphNode pNode=q.poll();
int size=pNode.neighbors.size();
pNode.neighbors.remove(size-1);
for(int i=0;i<size-1;i++){
UndirectedGraphNode neighbor=pNode.neighbors.get(i);
if(!visit.contains(neighbor.label)){
q.offer(neighbor);
visit.add(neighbor.label);
}
}
}
return root;
}
public static void main(String[] args) {
Solution sln = new Solution();
UndirectedGraphNode node=new UndirectedGraphNode(0);
node.neighbors.add(node);
node.neighbors.add(node);
sln.cloneGraph(node);
}
}
注意点
处理图为空的情况。