Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <limits.h>
  5.  
  6. struct Edge
  7. {
  8. int source, destination, weight;
  9. };
  10.  
  11. struct Graph
  12. {
  13. int V, E;
  14. struct Edge* edge;
  15. };
  16.  
  17. struct Graph* createGraph(int V, int E)
  18. {
  19. struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph));
  20.  
  21. graph->V = V;
  22.  
  23. graph->E = E;
  24.  
  25. graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
  26.  
  27. return graph;
  28. }
  29.  
  30. void FinalSolution(int dist[], int n)
  31. {
  32. printf("\nVertex\tDistance from Source Vertex\n");
  33. int i;
  34.  
  35. for (i = 0; i < n; ++i){
  36. printf("%d \t\t %d\n", i, dist[i]);
  37. }
  38. }
  39.  
  40. void BellmanFord(struct Graph* graph, int source)
  41. {
  42. int V = graph->V;
  43.  
  44. int E = graph->E;
  45.  
  46. int StoreDistance[V];
  47.  
  48. int i,j;
  49.  
  50. for (i = 0; i < V; i++)
  51. StoreDistance[i] = INT_MAX;
  52.  
  53. StoreDistance[source] = 0;
  54.  
  55. for (i = 1; i <= V-1; i++)
  56. {
  57. for (j = 0; j < E; j++)
  58. {
  59. int u = graph->edge[j].source;
  60.  
  61. int v = graph->edge[j].destination;
  62.  
  63. int weight = graph->edge[j].weight;
  64.  
  65. if (StoreDistance[u] + weight < StoreDistance[v])
  66. StoreDistance[v] = StoreDistance[u] + weight;
  67. }
  68. }
  69.  
  70. for (i = 0; i < E; i++)
  71. {
  72. int u = graph->edge[i].source;
  73.  
  74. int v = graph->edge[i].destination;
  75.  
  76. int weight = graph->edge[i].weight;
  77.  
  78. if (StoreDistance[u] + weight < StoreDistance[v])
  79. printf("This graph contains negative edge cycle\n");
  80. }
  81.  
  82. FinalSolution(StoreDistance, V);
  83.  
  84. return;
  85. }
  86.  
  87. int main()
  88. {
  89. int V, E, S;
  90.  
  91. printf("Enter number of vertices in graph\n");
  92. scanf("%d", &V);
  93.  
  94. printf("Enter number of edges in graph\n");
  95. scanf("%d", &E);
  96.  
  97. printf("Enter your source vertex number\n");
  98. scanf("%d", &S);
  99.  
  100. struct Graph* graph = createGraph(V, E);
  101.  
  102. int i;
  103. for(i = 0; i < E; i++){
  104. printf("Enter edge %d properties Source, destination, weight respectively\n",i+1);
  105. scanf("%d", &graph->edge[i].source);
  106. scanf("%d", &graph->edge[i].destination);
  107. scanf("%d", &graph->edge[i].weight);
  108. }
  109.  
  110. BellmanFord(graph, S);
  111.  
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement