Complete the code to initialize the adjacency list for the graph.
List<int>[] graph = new List<int>[n]; for (int i = 0; i < n; i++) { graph[i] = new [1]<int>(); }
We use List<int> to store neighbors for each node in the adjacency list.
Complete the code to add an undirected edge between two nodes u and v.
graph[u].Add([1]);
graph[v].Add(u);We add v to u's list and u to v's list to represent an undirected edge.
Fix the error in the DFS method signature for cycle detection.
bool DFS(int node, int parent, bool[] visited, List<int>[] graph) {
visited[node] = true;
foreach (int neighbor in graph[node]) {
if (!visited[neighbor]) {
if (DFS(neighbor, [1], visited, graph))
return true;
} else if (neighbor != parent) {
return true;
}
}
return false;
}When calling DFS recursively, the current node becomes the parent for the neighbor.
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; } } }
We loop from 0 to n-1 and start DFS with parent as -1 (no parent).
Fill all three blanks to complete the cycle detection method.
public bool HasCycle(int n, List<int>[] graph) {
bool[] visited = new bool[[1]];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
if (DFS(i, [2], visited, graph)) {
return [3];
}
}
}
return false;
}We create a visited array of size n, start DFS with parent -1, and return true if a cycle is found.
