Loading…
DAA · Graphs · Program 25 · In the record
Write a program in c to find the shortest path from a source vertex to all other vertices using the Bellman-Ford algorithm and find its execution time using the time function.
Algorithm: BELLMAN-FORD(G, w, s) 1. Start 2. For each vertex v in G do 3. d[v] <- infinity 4. p[v] <- NIL 5. d[s] <- 0 6. For i <- 1 to n-1 do 7. For each edge (u,v) in G do 8. if d[u] + w(u,v) < d[v] then 9. d[v] <- d[u] + w(u,v) 10. p[v] <- u 11. For each edge (u,v) in G do 12. if d[u] + w(u,v) < d[v] then 13. print "Graph contains a negative weight cycle" 14. Stop 15. Print d[v] and the path to every vertex v using p 16. Stop
1#include<stdio.h>2#include<time.h>3#define INF 999994 5int p[50];6 7void path(int v) {8 if(p[v]==0) {9 printf("%d",v);10 return;11 }12 path(p[v]);13 printf(" -> %d",v);14}15 16int main() {17 int n,e,i,j,s,neg=0,count=0;18 printf("Enter the number of vertices:");19 scanf("%d",&n);20 printf("Enter the number of edges:");21 scanf("%d",&e);22 int u[e],v[e],w[e],d[n+1];23 printf("Enter the edges (source destination weight):\n");24 for(j=0;j<e;j++)25 scanf("%d%d%d",&u[j],&v[j],&w[j]);26 printf("Enter the source vertex:");27 scanf("%d",&s);28 29 clock_t start=clock();30 for(i=1;i<=n;i++) {31 d[i]=INF;32 p[i]=0;33 }34 d[s]=0;35 for(i=1;i<=n-1;i++)36 for(j=0;j<e;j++) {37 count++;38 if(d[u[j]]!=INF && d[u[j]]+w[j]<d[v[j]]) {39 d[v[j]]=d[u[j]]+w[j];40 p[v[j]]=u[j];41 }42 }43 for(j=0;j<e;j++) {44 count++;45 if(d[u[j]]!=INF && d[u[j]]+w[j]<d[v[j]]) {46 neg=1;47 break;48 }49 }50 clock_t end=clock();51 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;52 53 if(neg)54 printf("\nGraph contains a negative weight cycle");55 else {56 printf("\nVertex\tDistance\tPath");57 for(i=1;i<=n;i++) {58 if(d[i]==INF)59 printf("\n%d\tunreachable",i);60 else {61 printf("\n%d\t%d\t\t",i,d[i]);62 path(i);63 }64 }65 }66 printf("\nNumber of comparisons:%d",count);67 printf("\nTime taken:%f seconds",time_taken);68 printf("\nTime complexity: O(VE)");69 printf("\nSpace complexity: O(V+E)");70 printf("\n");71 return 0;72}5 ⏎ 10 ⏎ 1 2 6 ⏎ 1 4 7 ⏎ 2 3 5 ⏎ 2 4 8 ⏎ 2 5 -4 ⏎ 3 2 -2 ⏎ 4 3 -3 ⏎ 4 5 9 ⏎ 5 1 2 ⏎ 5 3 7 ⏎ 1Enter the number of vertices:5 Enter the number of edges:10 Enter the edges (source destination weight): 1 2 6 1 4 7 2 3 5 2 4 8 2 5 -4 3 2 -2 4 3 -3 4 5 9 5 1 2 5 3 7 Enter the source vertex:1 Vertex Distance Path 1 0 1 2 2 1 -> 4 -> 3 -> 2 3 4 1 -> 4 -> 3 4 7 1 -> 4 5 -2 1 -> 4 -> 3 -> 2 -> 5 Number of comparisons:50 Time taken:0.000009 seconds Time complexity: O(VE) Space complexity: O(V+E)
Run program 25 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.