Skip to content

Commit

Permalink
Updated the Floyd Warshall Algorithm in single file
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhik004 committed Oct 18, 2024
1 parent 31a645b commit a155069
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 62 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/*
QUESTION -- Floyd Warshall Algorithm
Expand Down Expand Up @@ -27,4 +28,67 @@ OUTPUT --
EXPLANATION --
In this example, the final matrix stores the shortest distances between all pairs of nodes. For instance, matrix[0][3] = 6 indicates that the shortest distance from node 0 to node 3 is 6. Similarly, matrix[2][1] = 8 shows the shortest distance from node 2 to node 1.
In general, matrix[i][j] is storing the shortest distance from node i to j.
In general, matrix[i][j] is storing the shortest distance from node i to j.
*/

#include <bits/stdc++.h>
using namespace std;

class Solver {
public:
void calculateShortestDistance(vector<vector<int>>& m) {
int size = m.size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (m[i][j] == -1) {
m[i][j] = 1e9;
}
if (i == j) m[i][j] = 0;
}
}

for (int k = 0; k < size; k++) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
m[i][j] = min(m[i][j], m[i][k] + m[k][j]);
}
}
}

for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (m[i][j] == 1e9) {
m[i][j] = -1;
}
}
}
}
};

int main() {
int n;
cout << "Enter the size of the matrix (n x n): ";
cin >> n;

vector<vector<int>> m(n, vector<int>(n));

cout << "Enter the matrix (use -1 for no direct path):\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> m[i][j];
}
}

Solver obj;
obj.calculateShortestDistance(m);

cout << "The shortest distances between each pair of vertices are:\n";
for (auto& row : m) {
for (auto& cell : row) {
cout << cell << " ";
}
cout << endl;
}

return 0;
}
61 changes: 0 additions & 61 deletions C++/Floyd-Warshall/FloydWarshall.cpp

This file was deleted.

0 comments on commit a155069

Please sign in to comment.