MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / GraphDeepCopy

Class GraphDeepCopy

java/Graphs/GraphDeepCopy.java:18–46  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16 */
17
18public class GraphDeepCopy {
19 public GraphNode graphDeepCopy(GraphNode node) {
20 if (node == null) {
21 return null;
22 }
23 Map<GraphNode, GraphNode> cloneMap = new HashMap<>();
24 return dfs(node, cloneMap);
25 }
26
27 private GraphNode dfs(GraphNode node, Map<GraphNode, GraphNode> cloneMap) {
28 // If this node was already cloned, then return this previously
29 // cloned node.
30 if (cloneMap.containsKey(node)) {
31 return cloneMap.get(node);
32 }
33 // Clone the current node.
34 GraphNode clonedNode = new GraphNode(node.val);
35 // Store the current clone to ensure it doesn't need to be created
36 // again in future DFS calls.
37 cloneMap.put(node, clonedNode);
38 // Iterate through the neighbors of the current node to connect
39 // their clones to the current cloned node.
40 for (GraphNode neighbor : node.neighbors) {
41 GraphNode clonedNeighbor = dfs(neighbor, cloneMap);
42 clonedNode.neighbors.add(clonedNeighbor);
43 }
44 return clonedNode;
45 }
46}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected