Recall that the outer loop iterates k
, the "intermediate" vertex though which the candidate path from i
to j
could go:
for k in 0..N-1
for i in 0..N-1
for j in 0..N-1
g[i,j] = min(g[i,j], g[i,k]+g[k,j])
Therefore, before all the iterations the partial solution (which at this point is equivalent to the unmodified adjacency matrix) represents a subset of the final solution where all shortest paths that go directly from i
to j
are represented.
After one iteration, the shortest paths that go through the first vertex (at index 0
) are added to the mix.
After K
iterations, the partial solution contains shortest paths that are either (1) direct, or (2) go through one or more vertexes from the set of {0..K-1}
, inclusive. Of course once K
reaches N
, the solution is complete.