forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFloydWarshell.cpp
43 lines (35 loc) · 996 Bytes
/
FloydWarshell.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
#include<bits/stdc++.h>
using namespace std;
void FloydWarshell(vector<vector<int>>&matrix,int n){
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(matrix[i][k] ==-1 || matrix[k][j]==-1) continue;
if(matrix[i][j]==-1){
matrix[i][j]=matrix[i][k]+matrix[k][j];
}
else
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++){
cout << matrix[i][j] << " ";
}
cout <<endl;
}
}
int main(){
int n;
cin >> n;
vector<vector<int>>matrix(n, vector<int>(n, -1));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin >> matrix[i][j];
}
}
cout<<"Matrix after performing FloydWarshell Algo:-"<<endl;
FloydWarshell(matrix,n);
return 0;
}