From 82aef7e226ced42a17bc84f44815284e8a7f398b Mon Sep 17 00:00:00 2001 From: Ankit Pandit Date: Wed, 30 Oct 2024 20:29:11 +0530 Subject: [PATCH] Added Floyd-Warshall Algorithm in cpp --- Algorithms/Floyd-Warshall Algorithm in cpp | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Algorithms/Floyd-Warshall Algorithm in cpp diff --git a/Algorithms/Floyd-Warshall Algorithm in cpp b/Algorithms/Floyd-Warshall Algorithm in cpp new file mode 100644 index 0000000..6d1a22b --- /dev/null +++ b/Algorithms/Floyd-Warshall Algorithm in cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +class Solution { + void shortest_distance(vector>&matrix) { + int n = matrix.size(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == -1) { + matrix[i][j] = 1e9; + } + if (i == j) matrix[i][j] = 0; + } + } + + for (int k = 0; k < n; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] = min(matrix[i][j], + matrix[i][k] + matrix[k][j]); + } + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 1e9) { + matrix[i][j] = -1; + } + } + } + } +}; + +int main() { + + int V = 4; + vector> matrix(V, vector(V, -1)); + matrix[0][1] = 2; + matrix[1][0] = 1; + matrix[1][2] = 3; + matrix[3][0] = 3; + matrix[3][1] = 5; + matrix[3][2] = 4; + + Solution obj; + obj.shortest_distance(matrix); + + for(auto row : matrix) { + for (auto cell : row) { + cout << cell << " "; + } + cout << endl; + } + + return 0; +}