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

Function dfs

kotlin/Graphs/GraphDeepCopy.kt:18–36  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16}
17
18fun dfs(node: GraphNode, cloneMap: MutableMap<GraphNode, GraphNode>): GraphNode {
19 // If this node was already cloned, then return this previously
20 // cloned node.
21 if (node in cloneMap) {
22 return cloneMap[node]!!
23 }
24 // Clone the current node.
25 val clonedNode = GraphNode(node.value)
26 // Store the current clone to ensure it doesn't need to be created
27 // again in future DFS calls.
28 cloneMap[node] = clonedNode
29 // Iterate through the neighbors of the current node to connect
30 // their clones to the current cloned node.
31 for (neighbor in node.neighbors) {
32 val clonedNeighbor = dfs(neighbor, cloneMap)
33 clonedNode.neighbors.add(clonedNeighbor)
34 }
35 return clonedNode
36}

Callers 1

graphDeepCopyFunction · 0.70

Calls 1

addMethod · 0.45

Tested by

no test coverage detected