The core of the algorithm is a procedure that computes the length of the shortest-paths between any pair of vertices.
In the worst case this can be done in
time. Once the lengths are computed, the paths can be reconstructed using a Las Vegas algorithm whose expected running time is
for
and
for
.
The Python code below assumes the input graph is given as a
-
adjacency matrix
with zeros on the diagonal. It defines the function APD which returns a matrix with entries
such that
is the length of the shortest path between the vertices
and
. The matrix class used can be any matrix class implementation supporting the multiplication, exponentiation, and indexing operators (for example numpy.matrix).
def apd(A, n: int):
"""Compute the shortest-paths lengths."""
if all(A[i][j] for i in range(n) for j in range(n) if i != j):
return A
Z = A**2
B = matrix(
[
[1 if i != j and (A[i][j] == 1 or Z[i][j] > 0) else 0 for j in range(n)]
for i in range(n)
]
)
T = apd(B, n)
X = T * A
degree = [sum(A[i][j] for j in range(n)) for i in range(n)]
D = matrix(
[
[
2 * T[i][j] if X[i][j] >= T[i][j] * degree[j] else 2 * T[i][j] - 1
for j in range(n)
]
for i in range(n)
]
)
return D
The base case tests whether the input adjacency matrix describes a complete graph, in which case all shortest paths have length
.