Complete the code to initialize an adjacency list for a graph with 3 nodes.
const graph: number[][] = [[], [], []]; graph[0].push([1]);
We add node 1 as a neighbor to node 0 to represent an edge from 0 to 1.
Complete the code to check if a node has been visited in a graph traversal.
const visited: boolean[] = [false, false, false]; if (!visited[[1]]) { visited[1] = true; }
We check if node 1 is visited before marking it true.
Fix the error in the code that tries to find the shortest path in a graph using BFS.
const queue: number[] = []; queue.push(0); while (queue.length > 0) { const node = queue.shift()[1]; // process node }
shift() is a function and must be called with parentheses to remove the first element.
Fill both blanks to update distances and enqueue neighbors during BFS shortest path search.
for (const neighbor of graph[node]) { if (distances[neighbor] === [1]) { distances[neighbor] = distances[node] [2] 1; queue.push(neighbor); } }
Distances start at -1 meaning unvisited. We add 1 to the current node's distance to update neighbor's distance.
Fill all three blanks to create a function that returns the shortest path length from start to end in a graph.
function shortestPath(graph: number[][], start: number, end: number): number {
const distances = Array(graph.length).fill([1]);
const queue: number[] = [];
distances[start] = 0;
queue.push(start);
while (queue.length > 0) {
const node = queue.shift()[2];
if (node === end) return distances[node];
for (const neighbor of graph[node]) {
if (distances[neighbor] === [3]) {
distances[neighbor] = distances[node] + 1;
queue.push(neighbor);
}
}
}
return -1;
}Initialize distances with -1 for unvisited nodes, call shift() with parentheses, and check for -1 to find unvisited neighbors.