Complete the code to create an adjacency list for a graph.
const graph = {};
graph['A'] = [1];The adjacency list for node 'A' should be an array of connected nodes, so ['B', 'C'] is correct.
Complete the code to add a new edge from node 'B' to node 'D'.
graph['B'].[1]('D');
In JavaScript arrays, the method to add an element at the end is push.
Fix the error in the function to find neighbors of a node.
function getNeighbors(node) {
return graph[[1]];
}We want to access the neighbors of the given node, so use the variable node without quotes.
Fill both blanks to check if a node has neighbors and return them.
function safeGetNeighbors(node) {
if (graph[[1]] [2] undefined) {
return graph[node];
} else {
return [];
}
}We check if graph[node] is not equal to undefined to confirm neighbors exist.
Fill all three blanks to create a function that finds the shortest path length using BFS.
function shortestPathLength(start, end) {
const queue = [[start, 0]];
const visited = new Set([start]);
while (queue.length > 0) {
const [node, distance] = queue.shift();
if (node === [1]) return distance;
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.[2]([neighbor, distance [3] 1]);
}
}
}
return -1;
}We compare node to end, add neighbors to the queue with push, and increase distance by 1 using +.
