Complete the code to initialize the adjacency list for the graph.
List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.[1](new ArrayList<>()); }
The adjacency list is a list of lists. We use add to add a new empty list for each node.
Complete the code to add an undirected edge between two nodes u and v.
graph.get(u).[1](v);
graph.get(v).add(u);To add an edge in the adjacency list, we use add to add the neighbor node.
Fix the error in the DFS method signature for cycle detection.
private boolean dfs(int node, int parent, boolean[] visited, List<List<Integer>> graph) {
if (visited[node]) {
return true;
}
visited[node] = true;
for (int neighbor : graph.[1](node)) {
if (neighbor != parent) {
if (dfs(neighbor, node, visited, graph)) {
return true;
}
}
}
return false;
}To access the neighbors of a node in the adjacency list, we use get(node).
Fill both blanks to complete the cycle detection loop over all nodes.
for (int i = 0; i < [1]; i++) { if (!visited[i]) { if (dfs(i, [2], visited, graph)) { return true; } } }
The loop runs from 0 to n-1 nodes. The parent of the starting node is set to -1 because it has no parent.
Fill all three blanks to complete the cycle detection method.
public boolean hasCycle(int n, List<List<Integer>> edges) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.[1](new ArrayList<>());
}
for (List<Integer> edge : edges) {
int u = edge.get(0);
int v = edge.get(1);
graph.get(u).[2](v);
graph.get(v).add(u);
}
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
if (dfs(i, [3], visited, graph)) {
return true;
}
}
}
return false;
}We add empty lists for each node, add edges using add, and start DFS with parent -1.
