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

Function dfs

python3/Graphs/graph_deep_copy.py:17–32  ·  view source on GitHub ↗
(node: GraphNode, clone_map = {})

Source from the content-addressed store, hash-verified

15 return dfs(node)
16
17def dfs(node: GraphNode, clone_map = {}) -> GraphNode:
18 # If this node was already cloned, then return this previously
19 # cloned node.
20 if node in clone_map:
21 return clone_map[node]
22 # Clone the current node.
23 cloned_node = GraphNode(node.val)
24 # Store the current clone to ensure it doesn't need to be created
25 # again in future DFS calls.
26 clone_map[node] = cloned_node
27 # Iterate through the neighbors of the current node to connect
28 # their clones to the current cloned node.
29 for neighbor in node.neighbors:
30 cloned_neighbor = dfs(neighbor, clone_map)
31 cloned_node.neighbors.append(cloned_neighbor)
32 return cloned_node

Callers 1

graph_deep_copyFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected