1. Source distance
Distance to the start node is zero; all others begin at Infinity.
dist[start] = 0Typorithm · hard
Step 1 of 8 · intro card
Graph Algorithms
Greedily finalize the closest unfinished node, then relax its edges — for non-negative weights.
Dijkstra finds shortest paths from one source in a weighted graph with non-negative edges.
Each round it finalizes the nearest unsettled node, knowing no later path can beat it.
Relaxing that node's edges may lower its neighbors' tentative distances.
Finalize the closest node each round.
Relax: dist[u] + w < dist[next].
Requires non-negative weights.
function dijkstra(graph, n, start) {
const dist = new Array(n).fill(Infinity);
dist[start] = 0;
const done = new Array(n).fill(false);
for (let i = 0; i < n; i += 1) {
let u = -1;
for (let v = 0; v < n; v += 1) {
if (!done[v] && (u === -1 || dist[v] < dist[u])) u = v;
}
if (dist[u] === Infinity) break;
done[u] = true;
for (const [next, weight] of graph[u]) {
if (dist[u] + weight < dist[next]) {
dist[next] = dist[u] + weight;
}
}
}
return dist;
}Connect each part of the code to the concept before you type.
Distance to the start node is zero; all others begin at Infinity.
dist[start] = 0Greedily choose the unfinished node with the smallest known distance.
if (!done[v] && (u === -1 || dist[v] < dist[u])) u = vOnce chosen, that node's shortest distance is settled forever.
done[u] = trueIf going through u is shorter, update the neighbor's distance.
if (dist[u] + weight < dist[next])Record the better distance found through u.
dist[next] = dist[u] + weightRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
distances · nodes A–F6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state