fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #define V 4
  5. #define N 99999
  6.  
  7. void printSolution(int dist[][V]);
  8.  
  9. void floydWarshall (int graph[][V])
  10. {
  11. int dist[V][V], i, j, k;
  12.  
  13. for (i = 0; i < V; i++)
  14. for (j = 0; j < V; j++)
  15. dist[i][j] = graph[i][j];
  16.  
  17. for (k = 0; k < V; k++)
  18. {
  19. for (i = 0; i < V; i++)
  20. {
  21. for (j = 0; j < V; j++)
  22. {
  23. if (dist[i][k] + dist[k][j] < dist[i][j])
  24. dist[i][j] = dist[i][k] + dist[k][j];
  25. }
  26. }
  27. }
  28.  
  29. printSolution(dist);
  30. }
  31.  
  32. void printSolution(int dist[][V])
  33. {
  34. cout<<"The following matrix shows the shortest distances"
  35. " between every pair of vertices \n";
  36. for (int i = 0; i < V; i++)
  37. {
  38. for (int j = 0; j < V; j++)
  39. {
  40. if (dist[i][j] == N)
  41. cout<<"N"<<" ";
  42. else
  43. cout<<dist[i][j]<<" ";
  44. }
  45. cout<<endl;
  46. }
  47. }
  48.  
  49. int main()
  50. {
  51. int graph[V][V] = { {0, 5, N, 10},
  52. {N, 0, 3, N},
  53. {N, N, 0, 1},
  54. {N, N, N, 0}
  55. };
  56.  
  57. floydWarshall(graph);
  58. return 0;
  59. }
Success #stdin #stdout 0s 4352KB
stdin
Standard input is empty
stdout
The following matrix shows the shortest distances between every pair of vertices 
0     5     8     9     
N     0     3     4     
N     N     0     1     
N     N     N     0