Given a reference to a node in a connected undirected graph, return a deep copy (clone). Each node has val and neighbors. HashMap maps original→clone; register clone before recursing to break cycles.
adjList = [[2,4],[1,3],[2,4],[1,3]][[2,4],[1,3],[2,4],[1,3]] (cloned)Putting the clone in the map before recursing into neighbors is critical. Otherwise, in a cycle (1↔2), DFS would: visit 1 → recurse to 2 → recurse to 1 → infinite recursion. With map: visit 1 → put clone1 → recurse to 2 → recurse to 1 → cache hit, return clone1.
Copying a node and then naively copying each neighbour runs forever, because the graph has cycles. We need to remember which nodes are already copied.
Use a hash map from each original node to its copy. When you visit a node, first check the map. If the node is already copied, return that copy, which also stops infinite loops. Otherwise create the copy, store it in the map, and then clone every neighbour and attach it.
Store the copy in the map before visiting neighbours. The map doubles as the visited set.
Run the animation above on your own input, or watch the 1:46 video explanation of Clone Graph with a dry run and Java code.