http://www.lintcode.com/en/problem/clone-graph/
https://leetcode.com/problems/clone-graph/description/
题目:完成图的深度复制(包含点和边)
解答:1、使用BFS获得图中所有的点;
2、遍历所有点,将图中每个点复制并存入HashMap中<旧点,新点>;
3、遍历所有点,将每个点的neighbor值依次放入其neighbors的arraylist中。
(先复制点,再复制点之间的关系)
第一次犯错:通过赋值的方式直接将旧节点的neighbors赋值给新节点。应该将其一个一个添加至新节点中;
第二次犯错:忘记考虑空集的情况;
代码:
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
//get all nodes;
Set<UndirectedGraphNode> nodes = new HashSet<>();
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.offer(node);
nodes.add(node);
while (!queue.isEmpty()) {
UndirectedGraphNode head = queue.poll();
for (UndirectedGraphNode newNode : head.neighbors) {
if (nodes.add(newNode)) {
queue.offer(newNode);
}
}
}
//copy node value;
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
for (UndirectedGraphNode singleNode : nodes) {
map.put(singleNode, new UndirectedGraphNode(singleNode.label));
}
//copy neighbours(edges);
for (UndirectedGraphNode singleNode : nodes) {
for (UndirectedGraphNode neighbor : singleNode.neighbors) {
UndirectedGraphNode newNeighbor = map.get
(neighbor);
map.get(singleNode).neighbors.add(newNeighbor);
}
}
return map.get(node);
}
if (node == null) {
return null;
}
//get all nodes;
Set<UndirectedGraphNode> nodes = new HashSet<>();
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.offer(node);
nodes.add(node);
while (!queue.isEmpty()) {
UndirectedGraphNode head = queue.poll();
for (UndirectedGraphNode newNode : head.neighbors) {
if (nodes.add(newNode)) {
queue.offer(newNode);
}
}
}
//copy node value;
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
for (UndirectedGraphNode singleNode : nodes) {
map.put(singleNode, new UndirectedGraphNode(singleNode.label));
}
//copy neighbours(edges);
for (UndirectedGraphNode singleNode : nodes) {
for (UndirectedGraphNode neighbor : singleNode.neighbors) {
UndirectedGraphNode newNeighbor = map.get
(neighbor);
map.get(singleNode).neighbors.add(newNeighbor);
}
}
return map.get(node);
}