Write a C program for Floyd Warshall Algorithm in a Graph.

BEGIN

 FOR ALL v ∈ V

  d[v][v] ← 0

 FOR ALL (u,v) ∈ E

  d[u][v] ← w(u,v)

 for k from 1 to |V|

  for i from 1 to |V|

   for j from 1 to |V|

    if d[i][j] > d[i][k] + d[k][j]

     d[i][j] ← d[i][k] + d[k][j]

    end if

END

#include <stdio.h>
#include <limits.h>

#define V 4 // Number of vertices

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

    // Initialize distance matrix
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            dist[i][j] = graph[i][j];
        }
    }

    // Main algorithm
    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] != INT_MAX && dist[k][j] != INT_MAX &&
                    dist[i][j] > dist[i][k] + dist[k][j]) {
                    dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }
    }

    // Print the shortest distances
    printf("Shortest distances between vertices:\n");
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            if (dist[i][j] == INT_MAX) {
                printf("INF ");
            } else {
                printf("%d ", dist[i][j]);
            }
        }
        printf("\n");
    }
}

int main() {
    int graph[V][V] = {
        {0, 5, INT_MAX, 10},
        {INT_MAX, 0, 3, INT_MAX},
        {INT_MAX, INT_MAX, 0, 1},
        {INT_MAX, INT_MAX, INT_MAX, 0}
    };

    floydWarshall(graph);

    return 0;
}

Shortest distances between vertices:
0 5 8 9 
INF 0 3 4 
INF INF 0 1 
INF INF INF 0 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.