|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// Function to display the matrix |
| 6 | +void showMatrix(const vector<vector<long>> &matrix, int numVertices) |
| 7 | +{ |
| 8 | + for (int i = 0; i < numVertices; i++) |
| 9 | + { |
| 10 | + for (int j = 0; j < numVertices; j++) |
| 11 | + { |
| 12 | + if (matrix[i][j] < 10) // For better alignment |
| 13 | + cout << " "; |
| 14 | + cout << matrix[i][j] << " "; |
| 15 | + } |
| 16 | + cout << endl; |
| 17 | + } |
| 18 | + cout << endl; |
| 19 | +} |
| 20 | + |
| 21 | +// Floyd-Warshall algorithm |
| 22 | +void floydWarshall(vector<vector<long>> &matrix, int n) |
| 23 | +{ |
| 24 | + for (int k = 0; k < n; k++) // Intermediary vertex |
| 25 | + { |
| 26 | + for (int i = 0; i < n; i++) // Origin vertex |
| 27 | + { |
| 28 | + for (int j = 0; j < n; j++) // Destination vertex |
| 29 | + { |
| 30 | + if (matrix[i][k] != LONG_MAX && // i -> k exists |
| 31 | + matrix[k][j] != LONG_MAX && // k -> j exists |
| 32 | + matrix[i][j] > matrix[i][k] + matrix[k][j]) // i -> j is shorter via k |
| 33 | + { |
| 34 | + matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +int main() |
| 42 | +{ |
| 43 | + int numVertices = 5; |
| 44 | + |
| 45 | + // Initialize matrix with given values |
| 46 | + vector<vector<long>> matrix = { |
| 47 | + {0, 2, 10, 5, 7}, |
| 48 | + {2, 0, 3, 3, 1}, |
| 49 | + {10, 3, 0, 1, 2}, |
| 50 | + {5, 3, 1, 0, LONG_MAX}, |
| 51 | + {7, 1, 2, 2, 0}}; |
| 52 | + |
| 53 | + // Display the original matrix |
| 54 | + cout << "Original matrix:" << endl; |
| 55 | + showMatrix(matrix, numVertices); |
| 56 | + |
| 57 | + // Apply Floyd-Warshall algorithm |
| 58 | + floydWarshall(matrix, numVertices); |
| 59 | + |
| 60 | + // Display the updated matrix |
| 61 | + cout << "Updated matrix:" << endl; |
| 62 | + showMatrix(matrix, numVertices); |
| 63 | + |
| 64 | + // Show all shortest paths in 3 columns: source, destination, shortest distance |
| 65 | + cout << "Source\tDestination\tShortest Distance" << endl; |
| 66 | + for (int i = 0; i < numVertices; i++) |
| 67 | + for (int j = 0; j < numVertices; j++) |
| 68 | + cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl; |
| 69 | + |
| 70 | + return 0; |
| 71 | +} |
0 commit comments