forked from Vaani-pathariya/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFloyddWarshal.cpp
49 lines (49 loc) · 1.1 KB
/
FloyddWarshal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<bits/stdc++.h>
using namespace std ;
void shortest_distance(vector<vector<int>>&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]=1e8;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int m=0;m<n;m++){
if (matrix[j][i]!=1e8 || matrix[i][m]!=1e8)
matrix[j][m]=min(matrix[j][m],matrix[j][i]+matrix[i][m]);
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if (matrix[i][j]==1e8){
matrix[i][j]=-1;
}
}
}
}
int main(){
int n;
cin>>n;
vector<vector<int>>matrix;
for(int i=0;i<n;i++){
vector<int>temp;
for(int j=0;j<n;j++){
int a;
cin>>a;
temp.push_back(a);
}
matrix.push_back(temp);
}
shortest_distance(matrix);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}