Advertisement
Tavxela

Untitled

Jun 12th, 2021
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6. const int V = 5;
  7. const int INF = 99999;
  8.  
  9. void print_solution(int dist[][V]);
  10.  
  11. void floyd_warshall(int graph[][V])
  12. {
  13.     /*
  14.         this function is designed to run the Floyd-Warshall algorithm on a given graph with an adjacency matrix
  15.     */
  16.     int dist[V][V], i, j, k;
  17.     for (i = 0; i < V; i++)
  18.         for (j = 0; j < V; j++)
  19.             dist[i][j] = graph[i][j];
  20.  
  21.     for (k = 0; k < V; k++) {
  22.         for (i = 0; i < V; i++) {
  23.             for (j = 0; j < V; j++) {
  24.                 if (dist[i][j] > (dist[i][k] + dist[k][j])
  25.                     && (dist[k][j] != INF
  26.                         && dist[i][k] != INF))
  27.                     dist[i][j] = dist[i][k] + dist[k][j];
  28.             }
  29.         }
  30.     }
  31.     print_solution(dist);
  32. }
  33.  
  34. void print_solution(int dist[][V])
  35. {
  36.     /*
  37.         this function will print the paths and their costs between all pairs of vertices
  38.     */
  39.     cout << "Shortes paths between every pair of vertices\n" << endl;
  40.     for (int i = 0; i < V; i++) {
  41.         for (int j = 0; j < V; j++) {
  42.             cout << setw(6);
  43.             if (dist[i][j] == INF)
  44.                 cout << "INF"
  45.                     << " ";
  46.             else
  47.                 cout << dist[i][j] << " ";
  48.         }
  49.         cout << endl;
  50.     }
  51. }
  52.  
  53. int main()
  54. {
  55.     int graph[V][V] = {
  56.         { 0, 5, INF, 17, INF },
  57.         { INF, 0, 3, INF, INF },
  58.         { -5, INF, 0, 1, INF },
  59.         { INF, INF, 25, 0, 1 },
  60.         { INF, 4, INF, INF, 0 }
  61.     };
  62.  
  63.     floyd_warshall(graph);
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement