Practice/Meta/Design a Graph Storage and Cloning System
CodingMust
Design and implement a deep copy mechanism for an undirected graph data structure. You are given a reference to a node in a connected undirected graph where each node contains an integer value and a list of its neighbors.
Your task is to create a completely independent copy of the entire graph, ensuring that:
The graph is represented using an adjacency list where each node contains:
val: an integer value for the nodeneighbors: a list of references to neighboring nodesNode class with value and neighbors propertiescloneGraph function that takes a node reference and returns the corresponding node in the cloned graphnull/None if the input is null/NoneExample 1:
Input: Node with val=1, no neighbors Output: New Node with val=1, no neighbors Explanation: Single isolated node is cloned with same value and empty neighbor list
Example 2:
Input: Graph [[2,4],[1,3],[2,4],[1,3]] Node 1 connects to nodes 2 and 4 Node 2 connects to nodes 1 and 3 Node 3 connects to nodes 2 and 4 Node 4 connects to nodes 1 and 3 Output: Deep copy with identical structure Explanation: All four nodes and their connections are duplicated in new graph
Example 3:
Input: null Output: null Explanation: Empty graph returns null
Example 4:
Input: Graph forming triangle [[2,3],[1,3],[1,2]] Node 1 connects to nodes 2 and 3 Node 2 connects to nodes 1 and 3 Node 3 connects to nodes 1 and 2 Output: Deep copy maintaining triangle structure Explanation: Cycle is properly handled without infinite recursion