Loading…
DAA · Graphs · Program 24 · In the record
Write a program in c to find the shortest paths between all pairs of vertices using the Floyd-Warshall algorithm and find its execution time using the time function.
Algorithm: FLOYD-WARSHALL(W) 1. Start 2. n <- number of vertices 3. For i <- 1 to n do 4. For j <- 1 to n do 5. if i == j then D[i][j] <- 0 6. else if there is an edge (i,j) then D[i][j] <- W[i][j] 7. else D[i][j] <- infinity 8. For k <- 1 to n do 9. For i <- 1 to n do 10. For j <- 1 to n do 11. if D[i][k] + D[k][j] < D[i][j] then 12. D[i][j] <- D[i][k] + D[k][j] 13. Print D 14. Stop
1#include<stdio.h>2#include<time.h>3#define INF 999994 5int main() {6 int n,i,j,k,count=0;7 printf("Enter the number of vertices:");8 scanf("%d",&n);9 int D[n+1][n+1];10 printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);11 for(i=1;i<=n;i++)12 for(j=1;j<=n;j++)13 scanf("%d",&D[i][j]);14 15 clock_t start=clock();16 for(i=1;i<=n;i++)17 for(j=1;j<=n;j++)18 if(i!=j && D[i][j]==0)19 D[i][j]=INF;20 for(k=1;k<=n;k++)21 for(i=1;i<=n;i++)22 for(j=1;j<=n;j++) {23 count++;24 if(D[i][k]!=INF && D[k][j]!=INF && D[i][k]+D[k][j]<D[i][j])25 D[i][j]=D[i][k]+D[k][j];26 }27 clock_t end=clock();28 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;29 30 printf("\nShortest distance matrix:\n");31 for(j=1;j<=n;j++)32 printf("\t%d",j);33 for(i=1;i<=n;i++) {34 printf("\n%d",i);35 for(j=1;j<=n;j++)36 if(D[i][j]==INF)37 printf("\tINF");38 else39 printf("\t%d",D[i][j]);40 }41 printf("\nNumber of comparisons:%d",count);42 printf("\nTime taken:%f seconds",time_taken);43 printf("\nTime complexity: O(V^3)");44 printf("\nSpace complexity: O(V^2)");45 printf("\n");46 return 0;47}4 ⏎ 0 3 0 7 ⏎ 8 0 2 0 ⏎ 5 0 0 1 ⏎ 2 0 0 0Enter the number of vertices:4 Enter the 4x4 weight matrix (0 for no edge): 0 3 0 7 8 0 2 0 5 0 0 1 2 0 0 0 Shortest distance matrix: 1 2 3 4 1 0 3 5 6 2 5 0 2 3 3 3 6 0 1 4 2 5 7 0 Number of comparisons:64 Time taken:0.000006 seconds Time complexity: O(V^3) Space complexity: O(V^2)
Run program 24 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.