DFS with an original → copy map
Time O(V + E) Space O(V)clone(n): if n is in the map return its copy; otherwise create the copy, store it in the map before visiting neighbours (this stops cycles), then add clone(neighbour) for each neighbour.
adjList = [[2,4],[1,3],[2,4],[1,3]]map (original → copy)(map)
Step 1/3Copy node 1 and store it in the map before looking at its neighbours.
import java.util.*;
class Solution {
private final Map<Node, Node> copies = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
Node seen = copies.get(node);
if (seen != null) return seen;
Node copy = new Node(node.val);
copies.put(node, copy); // store before recursing: stops cycles
for (Node nb : node.neighbors) copy.neighbors.add(cloneGraph(nb));
return copy;
}
}Verdict: The map is both the visited set and the lookup for copies.