Clone Graph
Given a reference to a node in a connected undirected graph, return a deep copy of the whole graph.
Open on LeetCode ↗Intuition
A plain traversal would loop forever on cycles, and copying a node twice would break the structure. The fix is one map: original node → its clone. Before copying a node, check the map — if a clone already exists, reuse it. The map is simultaneously the visited-set and the wiring table that keeps every edge pointing at the right copy.
Approach
Why naive copy fails
Recursively copying neighbors with no memory loops forever on any cycle (A→B→A→…), and even without cycles a node reachable by two paths would be duplicated.
Map originals to clones
Keep seen[original] = clone. On visiting a node: if it is in the map, return the existing clone. Otherwise create the clone first, register it, then fill its neighbor list recursively — registering before recursing is what breaks cycles.
DFS or BFS both work
The traversal order does not matter; only the map does. DFS is shorter; BFS avoids deep recursion on long chains.
Solution & live demo
Edge cases
Return null immediately.
Clone made, empty neighbor list, no recursion.
Clone registered in the map before recursing, so the cycle hits the map and stops.