Intuition
Traverse the adjacency list using recursive DFS. Build the cloned adjacency list node by node, using a visited set to avoid revisiting.
Explanation
Brute Force
Perform a DFS from node 1. For each node visited, copy its neighbor list into the result. Use a visited set to avoid infinite loops in the undirected graph.
This is effectively the same complexity as BFS but uses recursion. Time is O(V + E) and space is O(V) for the visited set plus O(V) recursion stack.
Note: For an adjacency list representation, DFS and BFS are both O(V + E). The "brute" label here reflects that DFS with recursion is the more straightforward first approach.
Implementation
import java.util.*;
class Solution {
public List<List<Integer>> cloneGraph(List<List<Integer>> adjList) {
if (adjList == null || adjList.isEmpty()) return new ArrayList<>();
int n = adjList.size();
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) result.add(new ArrayList<>());
boolean[] visited = new boolean[n];
dfs(0, adjList, result, visited);
return result;
}
private void dfs(int u, List<List<Integer>> adjList, List<List<Integer>> result, boolean[] visited) {
if (visited[u]) return;
visited[u] = true;
result.set(u, new ArrayList<>(adjList.get(u)));
for (int v : adjList.get(u)) {
dfs(v - 1, adjList, result, visited);
}
}
}