1. k is outermost
k is the intermediate node allowed so far; it must be the outermost loop.
for (let k = 0; k < n; k += 1)Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Compute all-pairs shortest paths with a triple loop, relaxing dist[i][j] through each intermediate node k, with k outermost.
Floyd-Warshall finds the shortest path between every pair of nodes in one pass.
It builds up the answer by allowing one more intermediate node k on each outer iteration.
For each pair (i, j) it checks whether routing through k beats the current best distance.
k must be the outermost loop.
Relax dist[i][j] through k.
Handles all pairs at once.
function floydWarshall(dist, n) {
for (let k = 0; k < n; k += 1) {
for (let i = 0; i < n; i += 1) {
for (let j = 0; j < n; j += 1) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
return dist;
}Connect each part of the code to the concept before you type.
k is the intermediate node allowed so far; it must be the outermost loop.
for (let k = 0; k < n; k += 1)i ranges over every possible source node.
for (let i = 0; i < n; i += 1)j ranges over every possible destination node.
for (let j = 0; j < n; j += 1)Going i to k to j may be shorter than the current best i to j.
if (dist[i][k] + dist[k][j] < dist[i][j])Record the shorter path that routes through intermediate node k.
dist[i][j] = dist[i][k] + dist[k][j]Read 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
Input6 × 6 directed distance matrix · rows / columns A through F
Follow temporary values, local state and supporting structures at this step.
↗ The 36-cell working table above is itself auxiliary memory. Input values are shown separately.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state