logo
Icon

Floyd Warshall Algorithm (All-Pairs Shortest Paths)

9 mins read

Last updated: 28 Feb 2025

5618 views

0%

  • Introduction
  • What is Floyd-Warshall Algorithm?
  • Key Concepts in Floyd-Warshall Algorithm
  • Pseudocode for Floyd-Warshall Algorithm
  • Example Walkthrough
  • Floyd-Warshall Algorithm Time Complexity
  • Floyd-Warshall Algorithm Space Complexity
  • Applications of Floyd-Warshall Algorithm
  • Floyd Warshall Algorithm Example With Solution
  • Floyd-Warshall Algorithm in C++
  • Floyd-Warshall Algorithm in Java
  • Floyd-Warshall Algorithm in Python
  • Floyd-Warshall vs Dijkstra vs Bellman-Ford Algorithms

Introduction

The Floyd-Warshall algorithm is a powerful tool used in computer science to find the shortest paths between all pairs of nodes in a weighted graph.

This algorithm is particularly useful when you need to know the shortest path for every possible pair of nodes, making it a key technique in solving all-pairs shortest path problems. Let’s learn how the Floyd-Warshall algorithm works and where it can be applied.

What is Floyd-Warshall Algorithm?

The Floyd-Warshall algorithm is a method used in computer science to find the shortest paths between all pairs of nodes in a graph. A graph is like a map that shows how different points (called nodes) are connected by lines (called edges). 

Each edge has a number, called a weight, that represents the distance or cost to travel between two nodes. The goal of the Floyd-Warshall algorithm is to find the shortest possible path between every pair of nodes in the graph.

The algorithm works by checking every possible path between the nodes and updating the shortest known distance between them. It repeats this process for each node in the graph until it has considered all possible paths, ensuring that the shortest path is found for every pair of nodes.

What is floyd-warshall algorithm?

Let’s understand with an easy example:

Imagine you are planning a trip to visit four cities: City A, City B, City C, and City D. You have a map that shows the direct distances between some of these cities, but not all of them are directly connected. 

The Floyd-Warshall algorithm can help you figure out the shortest route between any two cities using the all pairs shortest path technique, even if the cities are not directly connected.

Key Concepts in Floyd-Warshall Algorithm

  • Dynamic Programming: This is a method used to solve problems by breaking them down into smaller, simpler subproblems. In the Floyd-Warshall algorithm, dynamic programming is used to update and keep track of the shortest paths between nodes by gradually improving the known distances as more paths are considered.

  • All-Pairs Shortest Paths: The Floyd-Warshall algorithm finds the shortest paths for all pairs of nodes in the graph, not just from one node to all others. This means that after running the algorithm, you know the shortest path between any two nodes in the graph.

  • Matrix Representation: The algorithm uses a matrix (a table with rows and columns) to represent the graph and store the distances between nodes. Each cell in the matrix represents the distance between two nodes. As the algorithm runs, it updates the matrix to reflect the shortest known distances between all pairs of nodes.

Pseudocode for Floyd-Warshall Algorithm

FloydWarshall(graph):
    Initialize dist[][] to the adjacency matrix of the graph
    for each vertex k in the graph:
        for each vertex i in the graph:
            for each vertex j in the graph:
                if dist[i][j] > dist[i][k] + dist[k][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
    return dist[][]
  • graph: The input graph represented by an adjacency matrix, where graph[i][j] is the weight of the edge from vertex i to vertex j.

  • dist[][]: A 2D matrix that stores the shortest path distances between all pairs of nodes.

The algorithm iteratively updates the shortest path between every pair of nodes by considering each node as an intermediate point.

Example Walkthrough

Let’s walk through an example using a simple graph with 4 nodes (A, B, C, D) and the following weighted edges:

A to B: 3

A to D: 7

B to C: 1

C to D: 2

D to B: 5

The graph can be represented as an adjacency matrix:

Example Walkthrough

Where "∞" represents that there is no direct path between the nodes.

Step 1: Initialization

Initialize the dist[][] matrix as the adjacency matrix of the graph.

Step 2: Iteration through all nodes (k)

  • For each node k, consider it as an intermediate node, and update the shortest paths.

Iteration with k = A:

Update distances considering A as an intermediate node:

  • No updates needed as there are no shorter paths through A.

Iteration with k = B:

Update distances considering B as an intermediate node:

  • dist[A][C] = min(dist[A][C], dist[A][B] + dist[B][C]) = min(∞, 3 + 1) = 4

  • dist[D][C] remains unchanged as there is no shorter path.

Updated matrix:

Updated matrix

Iteration with k = C:

Update distances considering C as an intermediate node:

  • dist[A][D] = min(dist[A][D], dist[A][C] + dist[C][D]) = min(7, 4 + 2) = 6

  • dist[B][D] = min(dist[B][D], dist[B][C] + dist[C][D]) = min(∞, 1 + 2) = 3

Updated matrix:

Updated matrix

Iteration with k = D:

Update distances considering D as an intermediate node:

  • dist[A][B] and dist[C][B] remain unchanged as there are no shorter paths through D.

Final matrix:

Final matrix

This matrix represents the shortest paths between all pairs of nodes.

Floyd-Warshall Algorithm Time Complexity

The time complexity of Floyd-Warshall algorithm is O(V^3). 

Aspect

Complexity

Explanation

Time Complexity

O(V^3)

The algorithm uses three nested loops, each iterating over the vertices (V), leading to O(V^3).

  • V represents the number of vertices in the graph.

  • The time complexity is O(V^3) because the algorithm checks all pairs of vertices for each possible intermediate vertex.

Floyd-Warshall Algorithm Space Complexity

The space complexity of Floyd-Warshall algorithm is O(V^2). 

Aspect

Complexity

Explanation

Space Complexity

O(V^2)

The algorithm uses a 2D matrix to store the shortest path distances between all pairs of nodes, requiring O(V^2) space.

 

The space complexity is O(V^2) due to the use of a matrix that stores the shortest path between every pair of vertices.

Applications of Floyd-Warshall Algorithm

  • Network Routing: Finds the shortest paths between all pairs of nodes in communication networks to optimize routing protocols.

  • Urban Planning: Helps in determining the most efficient routes between multiple locations in a city for infrastructure development.

  • Traffic Management: Assists in calculating the shortest travel paths between intersections in road networks.

  • Social Network Analysis: Used to determine the shortest connection paths between individuals in social networks.

  • Computer Graphics: Computes shortest paths in 3D meshes for rendering and animation.

  • Telecommunications: Optimizes signal transmission paths across various nodes in telecommunication networks.

  • Flight Scheduling: Determines the shortest flight routes between multiple airports for airlines.

  • Game Development: Used in pathfinding algorithms to determine the shortest route between points in a game environment.

Floyd Warshall Algorithm Example With Solution

Problem 1: Network Latency Optimization

Scenario: A company wants to optimize data transmission between multiple data centers across different cities. Each city is connected to others with varying latencies. The goal is to find the shortest latency path between every pair of data centers to ensure efficient communication.

Solution: Use the Floyd-Warshall algorithm to compute the shortest path between all pairs of data centers, optimizing the overall network latency.

Problem 2: Urban Traffic Planning

Scenario: A city planner needs to design a traffic system that minimizes the travel time between various intersections. Each road has a different travel time, and the planner wants to ensure that the shortest routes between all intersections are identified.

Solution: Apply the Floyd-Warshall algorithm to find the shortest travel times between all intersections, aiding in traffic signal placement and route optimization.

Problem 3: Social Network Analysis

Scenario: A social network platform wants to analyze the strength of connections between users. The platform needs to determine the shortest path between every pair of users based on their interactions or mutual friends.

Solution: The Floyd-Warshall algorithm can be used to calculate the shortest paths between all pairs of users, allowing the platform to understand and visualize the network's structure.

Floyd-Warshall Algorithm in C++

#include <iostream>
#include <vector>
#include <limits.h>

using namespace std;

#define V 4
#define INF INT_MAX

void floydWarshall(int graph[V][V]) {
    int dist[V][V];

    for (int i = 0; i < V; i++)
        for (int j = 0; j < V; j++)
            dist[i][j] = graph[i][j];

    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
            }
        }
    }

    cout << "Shortest distances between every pair of vertices:\n";
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            if (dist[i][j] == INF)
                cout << "INF ";
            else
                cout << dist[i][j] << "   ";
        }
        cout << endl;
    }
}

int main() {
    int graph[V][V] = {
        {0, 3, INF, 7},
        {8, 0, 2, INF},
        {5, INF, 0, 1},
        {2, INF, INF, 0}
    };

    floydWarshall(graph);
    return 0;
}

Floyd-Warshall Algorithm in Java

public class FloydWarshall {
    final static int INF = 99999, V = 4;

    void floydWarshall(int graph[][]) {
        int dist[][] = new int[V][V];

        for (int i = 0; i < V; i++)
            for (int j = 0; j < V; j++)
                dist[i][j] = graph[i][j];

        for (int k = 0; k < V; k++) {
            for (int i = 0; i < V; i++) {
                for (int j = 0; j < V; j++) {
                    if (dist[i][k] + dist[k][j] < dist[i][j])
                        dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }

        printSolution(dist);
    }

    void printSolution(int dist[][]) {
        System.out.println("Shortest distances between every pair of vertices:");
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (dist[i][j] == INF)
                    System.out.print("INF ");
                else
                    System.out.print(dist[i][j] + "   ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int graph[][] = {
            {0, 3, INF, 7},
            {8, 0, 2, INF},
            {5, INF, 0, 1},
            {2, INF, INF, 0}
        };
        FloydWarshall fw = new FloydWarshall();
        fw.floydWarshall(graph);
    }
}

Floyd-Warshall Algorithm in Python

V = 4
INF = float('inf')

def floydWarshall(graph):
    dist = list(map(lambda i: list(map(lambda j: j, i)), graph))

    for k in range(V):
        for i in range(V):
            for j in range(V):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    printSolution(dist)

def printSolution(dist):
    print("Shortest distances between every pair of vertices:")
    for i in range(V):
        for j in range(V):
            if dist[i][j] == INF:
                print("INF", end=" ")
            else:
                print(dist[i][j], end=" ")
        print()

if __name__ == "__main__":
    graph = [
        [0, 3, INF, 7],
        [8, 0, 2, INF],
        [5, INF, 0, 1],
        [2, INF, INF, 0]
    ]
    floydWarshall(graph)

Floyd-Warshall vs Dijkstra vs Bellman-Ford Algorithms

Aspect

Floyd-Warshall Algorithm

Dijkstra’s Algorithm

Bellman-Ford Algorithm

Purpose

Finds the shortest paths between all pairs of nodes

Finds the shortest path from a single source to all other nodes

Finds the shortest path from a single source to all other nodes

Graph Type

Weighted, directed or undirected, with positive or negative weights

Weighted, directed or undirected, with non-negative weights

Weighted, directed or undirected, with positive or negative weights

Handles Negative Weights

Yes, but cannot handle negative weight cycles

No

Yes, and can detect negative weight cycles

Time Complexity

O(V^3)

O((V + E) log V) with a priority queue

O(V * E)

Space Complexity

O(V^2)

O(V) with a priority queue

O(V)

Best for

Dense graphs or when all-pairs shortest paths are needed

Sparse graphs or when shortest path from a single source is needed

Graphs with negative weights or where negative weight cycle detection is needed

Algorithm Type

Dynamic Programming

Greedy

Dynamic Programming

Updates Distances

Iteratively updates the distance matrix for all pairs of nodes

Iteratively relaxes edges from the source node

Iteratively relaxes all edges V-1 times

Output

Matrix of shortest paths between all pairs of nodes

Shortest path distances from source to all other nodes

Shortest path distances from source to all other nodes

Use Case Examples

Network routing with multiple connections, traffic management

GPS navigation, shortest path in road networks

Finding shortest paths in graphs with negative weights, detecting negative cycles

Optimality

Provides exact shortest paths for all pairs of nodes

Provides exact shortest paths from source to all other nodes

Provides exact shortest paths from source to all other nodes

Yes, the Floyd-Warshall algorithm can handle negative edge weights. However, it cannot handle graphs with negative weight cycles, as the presence of such cycles would cause the algorithm to produce incorrect results.

After running the algorithm, if the distance from any node to itself becomes negative (i.e., dist[i][i] < 0), it indicates the presence of a negative weight cycle.

The Floyd-Warshall algorithm is most suitable for dense graphs or when you need to find the shortest paths between all pairs of nodes.

Floyd-Warshall finds the all-pairs shortest paths (or the shortest paths between all pairs of nodes), while Dijkstra's algorithm finds the shortest path from a single source node to all other nodes.

Yes, the Floyd-Warshall algorithm is based on dynamic programming, where the solution to a problem is built incrementally by solving smaller subproblems and combining their solutions.

Yes, the Floyd-Warshall algorithm can be applied to undirected graphs. However, each edge should be represented as two directed edges (one in each direction) in the adjacency matrix.

The algorithm's limitations include its O(V^3) time complexity, which makes it inefficient for very large graphs, and its inability to handle graphs with negative weight cycles.

Yes, the Floyd-Warshall algorithm can be parallelized because each iteration of the algorithm's three nested loops can be computed independently.

If two nodes are not connected, their distance remains infinite (often represented as a very large number in the matrix).

While effective for dense graphs, the Floyd-Warshall algorithm is not optimal for very large sparse graphs, where algorithms like Dijkstra's or Bellman-Ford may be more efficient.

Updated - 28 Feb 20259 mins readPublished : 19 Sep 2024

Bellman-Ford Algorithm: Example, Time Complexity, Code

Dynamic Programming (With Problems & Key Concepts)

0%