codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

24 / 65 topics
22Dijkstra's Algorithm23Bellman-Ford Algorithm24Floyd-Warshall Algorithm
Tutorials/Data Structures & Algorithms/Floyd-Warshall Algorithm
🧮Data Structures & Algorithms

Floyd-Warshall Algorithm

Updated 2026-04-20
3 min read

Floyd-Warshall Algorithm

The Floyd-Warshall algorithm is a classic graph theory algorithm used for finding the shortest paths between all pairs of vertices in a weighted graph. It is particularly useful when dealing with graphs that may contain negative weights, provided they do not contain any negative weight cycles.

Overview

  • Purpose: To find the shortest paths between all pairs of nodes in a graph.
  • Graph Type: Works for both directed and undirected graphs with non-negative or negative edge weights (no negative cycles).
  • Complexity: O(V^3), where V is the number of vertices in the graph.

Key Concepts

Graph Representation

The algorithm operates on an adjacency matrix representation of a graph. Each element graph[i][j] represents the weight of the direct edge from vertex i to vertex j. If there is no direct edge, it is typically represented by infinity (∞).

Dynamic Programming Approach

Floyd-Warshall uses dynamic programming to iteratively improve the shortest path estimates between all pairs of vertices. The core idea is to consider each vertex as an intermediate point and update the shortest paths accordingly.

Algorithm Steps

  1. Initialization:

    • Initialize a distance matrix dist with the same dimensions as the adjacency matrix.
    • Copy the weights from the adjacency matrix into the dist matrix.
    • Set the diagonal elements (dist[i][i]) to 0, representing the distance from a vertex to itself.
  2. Iterative Relaxation:

    • For each pair of vertices (i, j), consider every other vertex k as an intermediate point.
    • Update the shortest path between i and j if a shorter path is found through k.
  3. Path Reconstruction (Optional):

    • Maintain a predecessor matrix to reconstruct the shortest paths.

Pseudocode

function FloydWarshall(graph):
    V = number of vertices in graph
    dist = copy of graph adjacency matrix
    pred = initialize with None or special value indicating no path

    for k from 0 to V-1:
        for i from 0 to V-1:
            for j from 0 to V-1:
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
                    pred[i][j] = k

    return dist, pred

Code Example

Here's a Python implementation of the Floyd-Warshall algorithm:

def floyd_warshall(graph):
    V = len(graph)
    dist = [row[:] for row in graph]  # Copy the graph matrix
    pred = [[None for _ in range(V)] for _ in range(V)]

    # Initialize predecessor matrix
    for i in range(V):
        for j in range(V):
            if i != j and graph[i][j] != float('inf'):
                pred[i][j] = i

    # Floyd-Warshall algorithm
    for k in range(V):
        for i in range(V):
            for j in range(V):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
                    pred[i][j] = pred[k][j]

    return dist, pred

# Example usage
graph = [
    [0, 3, float('inf'), 7],
    [8, 0, 2, float('inf')],
    [5, float('inf'), 0, 1],
    [2, float('inf'), float('inf'), 0]
]

distances, predecessors = floyd_warshall(graph)
print("Shortest distances:")
for row in distances:
    print(row)

print("\nPredecessors for path reconstruction:")
for row in predecessors:
    print(row)

Best Practices

  1. Input Validation: Ensure the input graph is correctly formatted and contains valid weights.
  2. Handling Infinity: Use float('inf') to represent non-existent edges, ensuring proper arithmetic operations.
  3. Path Reconstruction: If path reconstruction is needed, maintain a predecessor matrix as shown in the code example.
  4. Complexity Consideration: The algorithm's cubic time complexity makes it suitable for graphs with up to several hundred vertices.

Real-World Applications

  • Routing Protocols: Used in network routing to find the shortest paths between nodes.
  • Transport Networks: Helps in optimizing routes in transportation systems.
  • Bioinformatics: Used in sequence alignment and phylogenetic tree construction.

Conclusion

The Floyd-Warshall algorithm is a powerful tool for solving the all-pairs shortest path problem. Its ability to handle graphs with negative weights (excluding cycles) makes it versatile across various domains. By understanding its implementation and best practices, you can effectively apply this algorithm in real-world scenarios.


PreviousBellman-Ford AlgorithmNext Kruskal's Algorithm

Recommended Gear

Bellman-Ford AlgorithmKruskal's Algorithm