Advertisement
Guest User

Untitled

a guest
Jul 28th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. INF 2 8 INF
  2. INF INF 3 4
  3. INF INF 0 7
  4. 5 INF INF 0
  5.  
  6. #include<stdio.h>
  7. #define V 4
  8. #define INF 99999
  9.  
  10. void path(int i, int j)
  11. {
  12. if (i==j)
  13. printf("%d",i);
  14. else
  15. if (t[i][j]==0)
  16. printf("No path found.n");
  17. else
  18. {
  19. path(i,t[i][j]);
  20. printf("%d",j);
  21. }
  22. }
  23. void floydWarshall (int graph[][V])
  24. {
  25. int dist[V][V], i, j, k, t[V][V];
  26.  
  27. for (i = 0; i < V; i++)
  28. for (j = 0; j < V; j++)
  29. dist[i][j] = graph[i][j];
  30.  
  31. for (i = 0; i < V; i++)
  32. for (j = 0; j < V; j++)
  33. {
  34. if(i==j || dist[i][j]==INF)
  35. t[i][j]=0;
  36. else
  37. t[i][j]=i+1;
  38. }
  39.  
  40. for (k = 0; k < V; k++)
  41. {
  42. for (i = 0; i < V; i++)
  43. {
  44. for (j = 0; j < V; j++)
  45. {
  46. if (dist[i][k] + dist[k][j] < dist[i][j]){
  47. dist[i][j] = dist[i][k] + dist[k][j];
  48. t[i][j]=t[k][j];
  49. }
  50. }
  51.  
  52. }
  53. }
  54. printf("nShortest paths matrix: n");
  55. pathMatrix(dist);
  56. printf("nPredecessor matrix: n");
  57. pathMatrix(t);
  58.  
  59. //How to call path reconstruction in this function?
  60.  
  61. for(i=0;i<V;i++)
  62. {
  63. for(j=0;j<V;j++)
  64. {
  65. if(i==j)
  66. {
  67. printf("nShortest cyclic path from %d. vertex: %d",i+1,dist[i][i]);
  68.  
  69. }
  70. }
  71. }
  72. }
  73.  
  74. void pathMatrix(int dist[][V])
  75. {
  76. for (int i = 0; i < V; i++)
  77. {
  78. for (int j = 0; j < V; j++)
  79. {
  80. if (dist[i][j] == INF)
  81. printf("%7s", "INF");
  82. else
  83. printf ("%7d", dist[i][j]);
  84. }
  85. printf("n");
  86. }
  87. }
  88.  
  89. void predMatrix(int t[][V])
  90. {
  91. for (int i = 0; i < V; i++)
  92. {
  93. for (int j = 0; j < V; j++)
  94. {
  95. printf ("%7d", t[i][j]);
  96. }
  97. printf("n");
  98. }
  99. }
  100.  
  101. int main()
  102. {
  103. int graph[V][V] = {{INF,2,8,INF},{INF,INF,3,4},{INF,INF,INF,7},{5,INF,INF,INF}};
  104. floydWarshall(graph);
  105. return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement