forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.java
65 lines (51 loc) · 1.93 KB
/
CloneGraph.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package Algorithms.bfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class CloneGraph {
class UndirectedGraphNode {
int label;
List<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x) {
label = x;
neighbors = new ArrayList<UndirectedGraphNode>();
}
};
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
HashMap<UndirectedGraphNode, UndirectedGraphNode> map =
new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
Queue<UndirectedGraphNode> qCopy = new LinkedList<UndirectedGraphNode>();
q.offer(node);
UndirectedGraphNode rootCopy = new UndirectedGraphNode(node.label);
qCopy.offer(rootCopy);
// BFS the graph.
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
UndirectedGraphNode curCopy = qCopy.poll();
// bfs all the childern node.
for (UndirectedGraphNode child : cur.neighbors) {
// the node has already been copied. Just connect it and don't
// need to copy.
if (map.containsKey(child)) {
curCopy.neighbors.add(map.get(child));
continue;
}
// put all the children into the queue.
q.offer(child);
// create a new child and add it to the parent.
UndirectedGraphNode childCopy = new UndirectedGraphNode(
child.label);
curCopy.neighbors.add(childCopy);
qCopy.offer(childCopy);
map.put(child, childCopy);
}
}
return rootCopy;
}
}