"""Floyd-Warshall all-pairs shortest paths.

Idea
----
Dynamic programming over "which intermediate nodes are allowed". After
processing node k, ``dist[i][j]`` is the shortest path from i to j that only
passes through nodes 0..k. Adding node k either helps (go i -> k -> j) or it
does not.

Complexity
----------
Time:  O(V^3)
Space: O(V^2)

When to use
-----------
Small dense graphs (a few hundred nodes) when you need every pair. A negative
value on the diagonal afterwards means a negative cycle.
"""

INF = float("inf")


def floyd_warshall(weights: list[list[float]]) -> list[list[float]]:
    """Return the all-pairs distance matrix for an adjacency matrix.

    Use ``float('inf')`` for "no edge". The input is not modified.
    """
    n = len(weights)
    dist = [row[:] for row in weights]
    for i in range(n):
        dist[i][i] = min(dist[i][i], 0)
    for k in range(n):
        dk = dist[k]
        for i in range(n):
            dik = dist[i][k]
            if dik == INF:
                continue
            di = dist[i]
            for j in range(n):
                if dik + dk[j] < di[j]:
                    di[j] = dik + dk[j]
    return dist
