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

Method dfs

java/Graphs/GraphDeepCopy.java:27–45  ·  view source on GitHub ↗
(GraphNode node, Map<GraphNode, GraphNode> cloneMap)

Source from the content-addressed store, hash-verified

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 1

graphDeepCopyMethod · 0.95

Calls 3

getMethod · 0.45
putMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected