-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathFloyd-Warshall.cpp
More file actions
52 lines (49 loc) · 876 Bytes
/
Floyd-Warshall.cpp
File metadata and controls
52 lines (49 loc) · 876 Bytes
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
50
51
52
Time Complexity: O(n^3)
Space Complexity: O(n^2)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m; // n-> Number of Vertices, m-> Number of unidirectional edges (u->v is not the same as v-> u)
cin>>n>>m;
int AdjList[n][n]; // Adjlist-> Adjacency list
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
AdjList[i][j]=(INT_MAX/10);
}
else
{
AdjList[i][i]=0;
}
}
}
for(int i=0;i<m;i++)
{
int u,v,x;
cin>>u>>v>>x; // edge from u to v (0 based indexing) with edge cost x;
AdjList[u][v]=x;
}
// Floyd-Warshall Algorithm
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
AdjList[i][j]=min(AdjList[i][k]+AdjList[k][j],AdjList[i][j]);
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<AdjList[i][j]<<" ";
}
cout<<endl;
}
}