Skip to content

Commit 076fafb

Browse files
authored
Merge pull request #269 from Abhishek-kumar82078/master
Added Floyd Warshall Algorithm in c++
2 parents b506325 + 6b952a0 commit 076fafb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Floyd Warshall Algorithm
2+
// A space efficient algorithm to find shortest distance in space complexity of (O(1))
3+
// Time complexity - O(v^3)
4+
5+
#include<bits/stdc++.h>
6+
using namespace std;
7+
8+
// Function which finds the shortest distance
9+
void shortest_distance(vector<vector<int>>&matrix)
10+
{
11+
// Making first loop as intermediate between two vertices
12+
for(int k=0;k<matrix.size();k++)
13+
{
14+
// Value of i is treated as starting vertex of edge
15+
for(int i=0;i<matrix.size();i++)
16+
{
17+
// Value of j is treated as starting vertex of edge
18+
for(int j=0;j<matrix.size();j++)
19+
{
20+
// Avoiding self edge as well as intermediate vertex which is same as either of the two vertices of edge
21+
if(k!=i && k!=j && i!=j)
22+
{
23+
// Not trying to put unavailable edge as intermediate edge And also adding edge if not available
24+
if(matrix[i][k]!=-1 && matrix[k][j]!=-1 && ((matrix[i][j] > (matrix[i][k]+matrix[k][j])) || matrix[i][j]==-1))
25+
matrix[i][j]=matrix[i][k]+matrix[k][j];
26+
}
27+
}
28+
29+
}
30+
}
31+
}
32+
33+
int main()
34+
{
35+
int v;
36+
cin>>v;
37+
vector<vector<int>>matrix(v,vector<int>(v,-1));
38+
for(int i=0;i<v;i++)
39+
{
40+
for(int j=0;j<v;j++)
41+
{
42+
cin>>matrix[i][j];
43+
}
44+
}
45+
shortest_distance(matrix);
46+
47+
// Printing the updated matrix
48+
for(int i=0;i<v;i++)
49+
{
50+
for(int j=0;j<v;j++)
51+
{
52+
cout<<matrix[i][j]<<" ";
53+
}
54+
cout<<endl;
55+
}
56+
return 0;
57+
}
58+
59+
// Description
60+
// This algorithm helps in finding shortest distance between
61+
// every pair of vertices in a given edge weighted directed Graph in in-place.
62+
// Core idea:- add any other vertex in between two edge and check if the previous distance
63+
// is greater than adding two edge connected with the intermediate edge, if yes update it.

0 commit comments

Comments
 (0)