fork download
  1. #include <stdio.h>
  2. #include <limits.h>
  3. #define INF INT_MAX
  4. #define V 4 // Number of vertices in the graph
  5. // Function to print the distance matrix
  6. void printSolution(int dist[V][V]);
  7. // Implementation of the Floyd-Warshall algorithm
  8. void floyd_warshall(int graph[V][V]) {
  9. int dist[V][V];
  10. int i, j, k;
  11. // Initialize the distance matrix with the given graph weights
  12. for (i = 0; i < V; i++) {
  13. for (j = 0; j < V; j++) {
  14. dist[i][j] = graph[i][j];
  15. }
  16. }
  17. // Compute shortest paths
  18. for (k = 0; k < V; k++) {
  19. for (i = 0; i < V; i++) {
  20. for (j = 0; j < V; j++) {
  21. if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
  22. dist[i][j] = dist[i][k] + dist[k][j];
  23. }
  24. }
  25. }
  26. }
  27. // Print the distance matrix
  28. printSolution(dist);
  29. }
  30. // Function to print the distance matrix
  31. void printSolution(int dist[V][V]) {
  32. printf("The shortest distances between every pair of vertices are:\n");
  33. for (int i = 0; i < V; i++) {
  34. for (int j = 0; j < V; j++) {
  35. if (dist[i][j] == INF)
  36. printf("%7s", "INF");
  37. else
  38. printf("%7d", dist[i][j]);
  39. }
  40. printf("\n");
  41. }
  42. }
  43. int main() {
  44. // Example graph represented as an adjacency matrix
  45. int graph[V][V] = { {0, 5, INF, 10},
  46. {INF, 0, 3, INF},
  47. {INF, INF, 0, 1},
  48. {INF, INF, INF, 0} };
  49. // Run the Floyd-Warshall algorithm
  50. floyd_warshall(graph);
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
The shortest distances between every pair of vertices are:
      0      5      8      9
    INF      0      3      4
    INF    INF      0      1
    INF    INF    INF      0