Floyd-Warshall Algorithm

Graph Selection

Playback Controls

Select start and target nodes to begin

Floyd-Warshall Info

Key Features:

  • • Finds all-pairs shortest paths
  • • Uses dynamic programming
  • • Time complexity: O(V³)
  • • Handles negative weights
  • • Detects negative cycles

Legend:

Current Intermediate Node
Processed Nodes
Being Examined
Shortest Path

Reference implementation of Floyd-Warshall Algorithm. Select a language tab to view and copy the code.

def floyd_warshall(dist: list[list[float]]) -> None:
    n = len(dist)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]

    # Detect negative-weight cycles
    for i in range(n):
        if dist[i][i] < 0:
            raise ValueError(f"Negative cycle through node {i}")

Python — Code Walkthrough

  1. float("inf") — safe with addition

    dist: list[list[float]]

    Using float("inf") for missing edges means dist[i][k] + dist[k][j] is float("inf") when either operand is inf — no overflow or guard needed. Python float arithmetic handles inf correctly.

  2. Three nested range loops

    for k in range(n): for i in range(n): for j in range(n):

    The k loop (intermediate vertex) must be outermost. If i or j were outermost, we would use future-state dist values before they are fully computed.

  3. f-string in error message

    raise ValueError(f"Negative cycle through node {i}")

    The f-string includes which node triggered the negative cycle, providing actionable information. Useful for debugging graph inputs.

  4. In-place modification — None return

    ) -> None

    The function modifies the passed matrix directly and returns None. The caller reads results from dist[][] after the function returns.