fork download
  1. #include <iostream>
  2. #include <climits>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. #define INF 99999
  7. void floydWarshall(int dist[][10], int V) {
  8.  
  9. for (int k = 0; k < V; k++) {
  10. for (int i = 0; i < V; i++) {
  11. for (int j = 0; j < V; j++) {
  12. if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j]) {
  13. dist[i][j] = dist[i][k] + dist[k][j];
  14. }
  15. }
  16. }
  17. }
  18.  
  19.  
  20. cout << "The shortest distance matrix is: \n";
  21. for (int i = 0; i < V; i++) {
  22. for (int j = 0; j < V; j++) {
  23. if (dist[i][j] == INF) {
  24. cout << "INF" << "\t";
  25. } else {
  26. cout << dist[i][j] << "\t";
  27. }
  28. }
  29. cout << endl;
  30. }
  31. }
  32.  
  33. int main() {
  34. int V, E;
  35.  
  36.  
  37. cout << "Enter the number of vertices: ";
  38. cin >> V;
  39. cout << "Enter the number of edges: ";
  40. cin >> E;
  41.  
  42.  
  43. int dist[10][10];
  44. for (int i = 0; i < V; i++) {
  45. for (int j = 0; j < V; j++) {
  46. if (i == j) {
  47. dist[i][j] = 0;
  48. } else {
  49. dist[i][j] = INF;
  50. }
  51. }
  52. }
  53.  
  54.  
  55. cout << "Enter the edges (source vertex, destination vertex, and weight):\n";
  56. for (int i = 0; i < E; i++) {
  57. int u, v, weight;
  58. cout << "Edge " << i + 1 << " (source destination weight): ";
  59. cin >> u >> v >> weight;
  60.  
  61.  
  62. dist[u][v] = weight;
  63. }
  64.  
  65.  
  66. floydWarshall(dist, 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 number of edges: Enter the edges (source vertex, destination vertex, and weight):
The shortest distance matrix is: