Complete the code to initialize the adjacency list for the graph.
const graph = Array.from({ length: n }, () => [1]);
We use an array of empty arrays to represent adjacency lists for each node.
Complete the code to add an edge between two nodes u and v in the undirected graph.
graph[u].push([1]);
graph[v].push(u);We add v to u's adjacency list and u to v's adjacency list to represent an undirected edge.
Fix the error in the DFS function to detect a cycle by correctly checking the parent node.
function dfs(node, parent) {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) {
if (dfs(neighbor, [1])) 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 function that iterates over all nodes.
for (let i = 0; i < n; i++) { if (!visited[i] && dfs([1], [2])) { return true; } } return false;
Start DFS from node i with parent -1 (no parent) to detect cycles in all components.
Fill all three blanks to complete the full cycle detection code snippet.
const visited = new Array(n).fill(false);
function dfs(node, parent) {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) {
if (dfs(neighbor, [1])) return true;
} else if (neighbor !== [2]) {
return true;
}
}
return false;
}
for (let i = 0; i < n; i++) {
if (!visited[i] && dfs([3], -1)) {
console.log('Cycle detected');
break;
}
}The DFS call passes current node as parent, checks neighbor not equal to parent, and starts DFS from i.
