FloydWarshall Algorithm in Python (original) (raw)

Floyd-Warshall Algorithm in Python

Last Updated : 23 Jul, 2025

The **Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen Warshall, is fundamental in computer science and graph theory. It is used to find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is highly efficient and can handle graphs with both positive and negative edge weights, making it a versatile tool for solving a wide range of network and connectivity problems.

The Floyd Warshall Algorithm is an all-pair shortest path algorithm, unlike Dijkstra and Bellman-Ford which are single source shortest path algorithms. This algorithm works for both the directed and undirected weighted graphs. However, it does not work for the graphs with negative cycles (where the sum of the edges in a cycle is negative). It follows the Dynamic Programming approach to check every possible path going via every possible node to calculate the shortest distance between every pair of nodes.

**Illustration:

Python `

Solves the all-pairs shortest path

problem using Floyd Warshall algorithm

def floydWarshall(graph): V = len(graph)

# Add all vertices one by one to
# the set of intermediate vertices.
for k in range(V):

    # Pick all vertices as source one by one
    for i in range(V):

        # Pick all vertices as destination
        # for the above picked source
        for j in range(V):

            # If vertex k is on the shortest path from
            # i to j, then update the value of graph[i][j]

            if ((graph[i][j] == -1 or 
                graph[i][j] > (graph[i][k] + graph[k][j]))
                and (graph[k][j] != -1 and graph[i][k] != -1)):
                graph[i][j] = graph[i][k] + graph[k][j]

if name == "main": graph = [ [0, 4, -1, 5, -1], [-1, 0, 1, -1, 6], [2, -1, 0, 3, -1], [-1, -1, 1, 0, 2], [1, -1, -1, 4, 0] ]

floydWarshall(graph)
for i in range(len(graph)):
    for j in range(len(graph)):
        print(graph[i][j], end=" ")
    print()

`

Output

0 4 5 5 7 3 0 1 4 6 2 6 0 3 5 3 7 1 0 2 1 5 5 4 0

**Time Complexity: O(V3), where V is the number of vertices in the graph and we run three nested loops each of size V

**Auxiliary Space: O(V2), to create a 2-D matrix in order to store the shortest distance for each pair of nodes.

**Read here for detailed analysis: complexity analysis of the Floyd Warshall algorithm