write a c Program to implement all pair shortest problem using dynamic programming technique

 


write a c Program to implement all pair shortest problem using dynamic programming technique

#include <stdio.h>

#include <limits.h>


#define MAX_NODES 100


void floydWarshall(int graph[MAX_NODES][MAX_NODES], int numNodes);


int main() {

    int graph[MAX_NODES][MAX_NODES];

    int numNodes, i, j;


    printf("Enter the number of nodes: ");

    scanf("%d", &numNodes);


    printf("Enter the adjacency matrix:\n");

    for (i = 0; i < numNodes; i++) {

        for (j = 0; j < numNodes; j++) {

            scanf("%d", &graph[i][j]);

        }

    }


    floydWarshall(graph, numNodes);


    return 0;

}


void floydWarshall(int graph[MAX_NODES][MAX_NODES], int numNodes) {

    int dist[MAX_NODES][MAX_NODES];

    int i, j, k;


    // Initialize the distance matrix

    for (i = 0; i < numNodes; i++) {

        for (j = 0; j < numNodes; j++) {

            dist[i][j] = graph[i][j];

        }

    }


    // Compute shortest paths for all pairs

    for (k = 0; k < numNodes; k++) {

        for (i = 0; i < numNodes; i++) {

            for (j = 0; j < numNodes; j++) {

                if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) {

                    dist[i][j] = dist[i][k] + dist[k][j];

                }

            }

        }

    }


    // Print the shortest distance matrix

    printf("Shortest distance matrix:\n");

    for (i = 0; i < numNodes; i++) {

        for (j = 0; j < numNodes; j++) {

            if (dist[i][j] == INT_MAX) {

                printf("INF\t");

            } else {

                printf("%d\t", dist[i][j]);

            }

        }

        printf("\n");

    }

}


No comments:

Post a Comment