Complete the code to initialize the distance array with Infinity for all vertices except the source.
const dist: number[] = new Array(V).fill([1]); dist[src] = 0;
We use Infinity to represent that initially all vertices are unreachable except the source which is set to 0.
Complete the code to perform the topological sort using DFS.
function topoSort(u: number, visited: boolean[], stack: number[], graph: Array<Array<[number, number]>>): void {
visited[u] = true;
for (const [v, w] of graph[u]) {
if (!visited[[1]]) {
topoSort(v, visited, stack, graph);
}
}
stack.push(u);
}u instead of the neighbor v.w as a visited index which is incorrect.We check if the adjacent vertex v is visited before calling DFS recursively.
Fix the error in the relaxation step inside the shortest path calculation.
for (const [v, w] of graph[u]) { if (dist[u] !== Infinity && dist[u] + w [1] dist[v]) { dist[v] = dist[u] + w; } }
We update the distance if the new path is shorter, so we check if dist[u] + w < dist[v].
Fill both blanks to complete the loop that processes vertices in topological order and relaxes edges.
while (stack.length > 0) { const u = stack.pop()!; if (dist[u] !== [1]) { for (const [v, w] of graph[u]) { if (dist[u] + w [2] dist[v]) { dist[v] = dist[u] + w; } } } }
The distance must not be Infinity to relax edges, and relaxation happens if the new distance is less than the current.
Fill all three blanks to complete the function that returns shortest distances from source in a DAG.
function shortestPathDAG(V: number, graph: Array<Array<[number, number]>>, src: number): number[] {
const dist: number[] = new Array(V).fill([1]);
dist[src] = 0;
const visited: boolean[] = new Array(V).fill(false);
const stack: number[] = [];
for (let i = 0; i < V; i++) {
if (!visited[i]) {
[2](i, visited, stack, graph);
}
}
while (stack.length > 0) {
const u = stack.pop()!;
if (dist[u] !== Infinity) {
for (const [v, w] of graph[u]) {
if (dist[u] + w [3] dist[v]) {
dist[v] = dist[u] + w;
}
}
}
}
return dist;
}Initialize distances with Infinity, call topoSort for unvisited vertices, and relax edges when the new distance is less than the current.