Graph Theory37 sections · 1633 units
Open in Course

LeetCode 133 Clone Graph - Handling Cycles

The Infinite Loop

Suppose node 11 connects to node 22, and node 22 connects back to node 11. When you clone node 11, you recurse into node 22. Cloning node 22 tries to recurse back into node 11. Without protection, this loops forever.

The fix: use a hash map from original nodes to their copies. Before cloning any node, check the map first. If the node already has a copy, return it immediately. This breaks the cycle. You must add each node to the map before recursing into its neighbors.