-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.java
More file actions
38 lines (36 loc) · 1.27 KB
/
CloneGraph.java
File metadata and controls
38 lines (36 loc) · 1.27 KB
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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
public class CloneGraph {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.add(node);
while (queue.size() > 0) {
UndirectedGraphNode n = queue.pollFirst();
ArrayList<UndirectedGraphNode> neighbors = n.neighbors;
if (!map.containsKey(n)) {
UndirectedGraphNode copy = new UndirectedGraphNode(n.label);
map.put(n, copy);
}
for (UndirectedGraphNode neighbor: neighbors) {
UndirectedGraphNode neighborCopy;
if (!map.containsKey(neighbor)) {
queue.add(neighbor);
neighborCopy = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, neighborCopy);
map.get(n).neighbors.add(neighborCopy);
}
else {
neighborCopy = map.get(neighbor);
map.get(n).neighbors.add(neighborCopy);
}
}
}
return map.get(node);
}
}