Advertisement
Guest User

Untitled

a guest
Mar 17th, 2021
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     int v;
  8.     cout<<"\nEnter the number of vertices: ";
  9.     cin>>v;
  10.     int adj[v][v];
  11.     long dist[v][v];
  12.     int next[v][v];
  13.  
  14.     for(auto i=0;i<v;i++)
  15.         for(auto j=0;j<v;j++)
  16.             cin>>adj[i][j];
  17.  
  18.     for(auto i=0;i<v;i++)
  19.     {
  20.         for(auto j=0;j<v;j++)
  21.         {
  22.             if(i==j)
  23.             {
  24.                 dist[i][j]=0;
  25.                 next[i][j]=i;
  26.             }
  27.             else if(adj[i][j])
  28.             {
  29.                 dist[i][j] = adj[i][j];
  30.                 next[i][j] = j;
  31.             }
  32.             else
  33.             {
  34.                 dist[i][j] = INT_MAX;
  35.                 next[i][j] = -1;
  36.             }
  37.         }
  38.     }
  39.    
  40.     for(auto k=0;k<v;k++)
  41.         for(auto i=0;i<v;i++)
  42.             for(auto j=0;j<v;j++)
  43.             {
  44.                 if(dist[i][j] > dist[i][k] + dist[k][j])
  45.                 {
  46.                     dist[i][j] = dist[i][k] + dist[k][j];
  47.                     next[i][j] = next[i][k];
  48.                 }
  49.             }
  50.     cout<<"\nThe Shortest Distances are: \n";
  51.  
  52.     for(auto i=0;i<v;i++)
  53.     {
  54.        for(auto j=0;j<v;j++)
  55.         {
  56.             cout<<dist[i][j]<<" ";
  57.         }
  58.         cout<<"\n";
  59.     }
  60.  
  61.     cout<<"\nThe Shortest Paths are: \n";
  62.       // for printing path
  63.       for(int i=0;i<v;i++)
  64.       {
  65.         for(int j=i+1;j<v;j++)
  66.         {
  67.           int u=i,v=j;
  68.           cout<<u;
  69.           while(u!=v)
  70.           {
  71.             u=next[u][v];
  72.             cout<<"->"<<u;  
  73.           }
  74.           cout<<"\n";
  75.         }
  76.       }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement