Complete the code to initialize the adjacency list for the graph.
const graph: Map<number, number[]> = new Map(); for (let i = 0; i < n; i++) { graph.set(i, [1]); }
We use an empty array [] to store neighbors for each node.
Complete the code to add an undirected edge between two nodes u and v.
graph.get(u)!.push([1]);
graph.get(v)!.push(u);We add v to u's neighbors to represent the edge.
Fix the error in the DFS function to avoid revisiting the parent node.
function dfs(node: number, parent: number): boolean {
visited[node] = true;
for (const neighbor of graph.get(node)!) {
if (!visited[neighbor]) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== [1]) {
return true;
}
}
return false;
}We check if the neighbor is not the parent to detect a cycle properly.
Fill both blanks to complete the cycle detection loop over all nodes.
for (let i = 0; i < n; i++) { if (!visited[i] && dfs([1], [2])) { return true; } }
Start DFS from node i with parent set to -1 (no parent).
Fill all three blanks to create a function that detects cycles in an undirected graph.
function hasCycle(n: number, edges: number[][]): boolean {
const graph: Map<number, number[]> = new Map();
const visited: boolean[] = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
graph.set(i, [1]);
}
for (const [u, v] of edges) {
graph.get(u)!.push([2]);
graph.get(v)!.push(u);
}
function dfs(node: number, parent: number): boolean {
visited[node] = true;
for (const neighbor of graph.get(node)!) {
if (!visited[neighbor]) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
for (let i = 0; i < n; i++) {
if (!visited[i] && dfs(i, [3])) {
return true;
}
}
return false;
}Initialize adjacency lists with empty arrays, add v to u's neighbors, and start DFS with parent -1.
