-
Notifications
You must be signed in to change notification settings - Fork 2
/
CloneGraph.java
41 lines (33 loc) · 1.36 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
package leetcode.graph;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import leetcode.helpers.UndirectedGraphNode;
public class CloneGraph {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
// Records a mapping from nodes in the original graph to those in the new graph.
Map<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
mapping.put(node, new UndirectedGraphNode(node.label));
// Performs a standard BFS (breadth-first search).
Queue<UndirectedGraphNode> toVisit = new LinkedList<>();
toVisit.add(node);
while (!toVisit.isEmpty()) {
UndirectedGraphNode current = toVisit.poll();
UndirectedGraphNode cloned = mapping.get(current);
for (UndirectedGraphNode neighbor: current.neighbors) {
UndirectedGraphNode clonedNeighbor = mapping.get(neighbor);
if (clonedNeighbor == null) {
toVisit.add(neighbor);
clonedNeighbor = new UndirectedGraphNode(neighbor.label);
mapping.put(neighbor, clonedNeighbor);
}
cloned.neighbors.add(clonedNeighbor);
}
}
return mapping.get(node);
}
}