Given a reference of a node in a **connected undirected graph**, return a **deep copy** (clone) of the graph.
Each node in the graph contains a value (val) and a list of its neighbors (neighbors).
Examples
adjList = [[2,4],[1,3],[2,4],[1,3]][[2,4],[1,3],[2,4],[1,3]]Constraints
The number of nodes in the graph is in the range [0, 100].1 <= Node.val <= 100Node.val is unique for each node.There are no repeated edges and no self-loops in the graph.
š” Hints
Hint 1
Use Breadth-First Search (BFS) with a queue and a hash map to map original nodes to their cloned counterparts.
Hint 2
For each neighbor of the current node, if it has not been cloned yet, clone it and push it to the queue.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Traverse the graph using BFS. Use a Hash Map to record visited nodes and store mapping from original node to cloned node.
BFS/DFS visits every unique node V and traverses each undirected edge E exactly once in O(V + E) time.
A hash map stores visited clones for up to V nodes, plus the traversal queue/stack holds up to V vertices.
š Real-World Use Cases
Deep-copying layers, vectors, and component hierarchy using graph BFS cloning.
š Dry Run
Initialize queue with Node 1 and clone Node 1 into the hash map.