Complete the code to initialize the distance array with Infinity for all vertices except the source.
const dist = new Array(V).fill([1]); dist[src] = 0;
We use Infinity to represent initially unknown distances, except the source which is 0.
Complete the code to perform topological sorting using DFS.
function topoSortUtil(u, visited, stack) {
visited[u] = true;
for (const [v] of graph[u]) {
if (!visited[v]) {
topoSortUtil(v, visited, stack);
}
}
stack.push([1]);
}v instead of current vertex uWe push the current vertex u onto the stack after visiting all its neighbors.
Fix the error in updating the distance of adjacent vertices in the shortest path calculation.
for (const [v, weight] of graph[u]) { if (dist[u] !== Infinity && dist[u] + weight [1] dist[v]) { dist[v] = dist[u] + weight; } }
We update dist[v] only if the new path is shorter, so we check if dist[u] + weight < dist[v].
Fill both blanks to correctly iterate over vertices in topological order and update distances.
while (stack.length > 0) { const u = stack.pop(); if (dist[u] !== [1]) { for (const [v, weight] of graph[u]) { if (dist[u] + weight [2] dist[v]) { dist[v] = dist[u] + weight; } } } }
We skip vertices with infinite distance and update neighbors if new distance is less than current.
Fill all three blanks to create a dictionary of shortest distances for vertices reachable from source.
const shortestPaths = {
[1]: dist[[2]] for [3] in [...Array(V).keys()] if dist[[3]] !== Infinity
};We map each vertex v to its distance dist[v] for all vertices v with finite distance.
