fork download
  1. #include <iostream>
  2. #include <climits>
  3. using namespace std;
  4.  
  5. #define INF 99999
  6.  
  7. void floydWarshall(int graph[][10], int V) {
  8.  
  9. int dist[V][V];
  10.  
  11.  
  12. for (int i = 0; i < V; i++) {
  13. for (int j = 0; j < V; j++) {
  14. if (graph[i][j] == 0 && i != j) {
  15. dist[i][j] = INF;
  16. } else {
  17. dist[i][j] = graph[i][j];
  18. }
  19. }
  20. }
  21.  
  22.  
  23. for (int k = 0; k < V; k++) {
  24. for (int i = 0; i < V; i++) {
  25. for (int j = 0; j < V; j++) {
  26. if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j]) {
  27. dist[i][j] = dist[i][k] + dist[k][j];
  28. }
  29. }
  30. }
  31. }
  32.  
  33.  
  34. cout << "The shortest distance matrix is: \n";
  35. for (int i = 0; i < V; i++) {
  36. for (int j = 0; j < V; j++) {
  37. if (dist[i][j] == INF) {
  38. cout << "INF" << "\t";
  39. } else {
  40. cout << dist[i][j] << "\t";
  41. }
  42. }
  43. cout << endl;
  44. }
  45. }
  46.  
  47. int main() {
  48. int V;
  49.  
  50.  
  51. cout << "Enter the number of vertices: ";
  52. cin >> V;
  53.  
  54.  
  55. int graph[10][10];
  56.  
  57.  
  58. cout << "Enter the adjacency matrix (enter 0 for no edge, non-zero values for edge weights):\n";
  59. for (int i = 0; i < V; i++) {
  60. for (int j = 0; j < V; j++) {
  61. cin >> graph[i][j];
  62. }
  63. }
  64.  
  65.  
  66. floydWarshall(graph, V);
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Enter the number of vertices: Enter the adjacency matrix (enter 0 for no edge, non-zero values for edge weights):
The shortest distance matrix is: