Open In App

Floyd-Warshall Algorithm in C

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs and can handle negative weights, provided there are no negative weight cycles.

In this article, we will learn about the working of the Floyd-Warshall algorithm, how to implement the Floyd-Warshall algorithm in C, and its applications.

Floyd-Warshall Algorithm for All-Pairs Shortest Paths in C

The Floyd-Warshall Algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a given weighted graph. It systematically updates the solution matrix to ensure that it eventually contains the shortest paths between all pairs of vertices.

Principle of Floyd-Warshall Algorithm

The principle behind the Floyd-Warshall algorithm is to use a matrix to keep track of the shortest paths between all pairs of vertices. The algorithm iteratively updates this matrix by considering each vertex as an intermediate point and checking if a shorter path exists through that vertex.

Floyd-Warshall Algorithm in C Language

The key idea is to improve the distance between any two vertices (i, j) by considering an intermediate vertex k. If the distance from i to j through k is shorter than the current known distance, update the distance.

dpFloyd-Warshall-
Floyd Warshall Algorithm

Below is the algorithm for finding the shortest paths between all pairs of vertices using the Floyd-Warshall algorithm:

  • Create a matrix dist[][] initialized with the input graph's weights. If there is no edge between vertices i and j, set dist[i][j] to infinity (or a large value).
  • For each pair of vertices (i, j), update dist[i][j] by considering each vertex k as an intermediate point. The update rule is:
    • if (dist[i][k] + dist[k][j] < dist[i][j])
    • dist[i][j] = dist[i][k] + dist[k][j];
  • Repeat the update step for all vertices k as intermediates to ensure all possible paths are considered.

Working of Floyd-Warshall Algorithm

Let us consider the below example of a graph and see how Floyd-Warshall algorithm will generate the minimum spanning tree(MST) for it step-by-step:

C Program to Implement Floyd Warshall Algorithm

The below program demonstrates how we can implement floyd warshall algorithm in C language.

C
// C Program for Floyd Warshall Algorithm
#include <stdio.h>

// Number of vertices in the graph
#define V 4

/* Define Infinite as a large enough
  value. This value will be used
  for vertices not connected to each other */
#define INF 99999

// A function to print the solution matrix
void printSolution(int dist[][V]);

// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
void floydWarshall(int dist[][V])
{
    int i, j, k;

    /* Add all vertices one by one to
      the set of intermediate vertices.
      ---> Before start of an iteration, we
      have shortest distances between all
      pairs of vertices such that the shortest
      distances consider only the
      vertices in set {0, 1, 2, .. k-1} as
      intermediate vertices.
      ----> After the end of an iteration,
      vertex no. k is added to the set of
      intermediate vertices and the set
      becomes {0, 1, 2, .. k} */
    for (k = 0; k < V; k++) {
        // Pick all vertices as source one by one
        for (i = 0; i < V; i++) {
            // Pick all vertices as destination for the
            // above picked source
            for (j = 0; j < V; j++) {
                // If vertex k is on the shortest path from
                // i to j, then update the value of
                // dist[i][j]
                if (dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
            }
        }
    }

    // Print the shortest distance matrix
    printSolution(dist);
}

/* A utility function to print solution */
void printSolution(int dist[][V])
{
    printf(
        "The following matrix shows the 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)
                printf("%7s", "INF");
            else
                printf("%7d", dist[i][j]);
        }
        printf("\n");
    }
}

// driver's code
int main()
{
    /* Let us create the following weighted graph
            10
       (0)------->(3)
        |         /|\
      5 |          |
        |          | 1
       \|/         |
       (1)------->(2)
            3           */
    int graph[V][V] = { { 0, 5, INF, 10 },
                        { INF, 0, 3, INF },
                        { INF, INF, 0, 1 },
                        { INF, INF, INF, 0 } };

    // Function call
    floydWarshall(graph);
    return 0;
}

Output
The following matrix shows the shortest distances between every pair of vertices 
      0      5      8      9
    INF      0      3      4
    INF    INF      0      1
    INF    INF    INF      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.

Applications of Floyd-Warshall Algorithm

The Floyd-Warshall algorithm is used in various applications:

  • To find the shortest paths in computer networks.
  • To compute the transitive closure of a graph.
  • For graphs where we need to find the shortest path between every pair of vertices.
  • To determine the shortest paths in transportation networks.
  • To find the shortest paths in game maps and terrains.

Related Articles

You can also go through the following related articles on floyd-warshall algorithms:


Next Article
Article Tags :

Similar Reads