An interactive visualization of deep copying an undirected graph using DFS. Watch how each node is cloned and connections are rebuilt using a visited hash map.
DFS LeetCode 133 โ Mediumint) and a list of its neighbors
(List[Node]). The graph is represented using an adjacency list where the index
of each list element corresponds to the node's value (1-indexed).fun cloneGraph(node: Node?): Node? { if (node == null) return null val visited = HashMap<Node, Node>() fun dfs(node: Node): Node { if (node in visited) return visited[node]!! val clone = Node(node.`val`) visited[node] = clone for (neighbor in node.neighbors) { clone.neighbors.add(dfs(neighbor!!)) } // all neighbors processed return clone } return dfs(node)}
DFS combined with a hash map (visited) prevents infinite loops in the graph
and ensures each node is cloned exactly once. The hash map maps each original node to its clone, so when
we encounter an already-visited neighbor, we simply return the cached clone instead of creating a duplicate.
None, return None.visited dictionary to track cloned nodes.visited, return the cached clone (prevents infinite recursion).Node with the same value.visited immediately (before processing neighbors).
We visit each node exactly once (V nodes) and traverse each edge exactly once (E edges).
The space is O(V) for the visited hash map and the recursion stack (at most V deep in a degenerate graph).