Complete the code to initialize the distance to the source node as zero.
distances[source] = [1];The distance from the source node to itself is always zero.
Complete the code to pick the unvisited node with the smallest distance.
let currentNode = unvisitedNodes.reduce((minNode, node) => distances[node] < distances[minNode] ? node : minNode, [1]);We use the first node in unvisitedNodes as the initial value to correctly find the minimum among unvisited nodes.
Fix the error in updating the distance if a shorter path is found.
if (distances[currentNode] + graph[currentNode][neighbor] [1] distances[neighbor]) { distances[neighbor] = distances[currentNode] + graph[currentNode][neighbor]; previous[neighbor] = currentNode; }
We update the distance only if the new path is shorter (less than current known distance).
Fill both blanks to correctly initialize distances and previous nodes for all nodes.
for (const node of nodes) { distances[node] = [1]; previous[node] = [2]; }
Distances start as Infinity because we don't know paths yet. Previous nodes start as null because no paths are known.
Fill all three blanks to build the shortest path by backtracking from the target node.
const path = []; let current = [1]; while (current !== [2]) { path.unshift(current); current = [3][current]; }
We start from the target node, backtrack until previous is null, using the previous map to find the path.
