forked from kjsce-codecell/Graph-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyd_warshall.cpp
50 lines (48 loc) · 1.19 KB
/
floyd_warshall.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
50
#include<bits/stdc++.h>
#define INF 999
#define n 4
using namespace std;
int fwgraph(int graph[n][n]) {
int k, shortdist[n][n],i,j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
shortdist[i][j]=graph[i][j];
//we initially define the shortest distance the same as the input distances, considering no intermediate vertices
}
//We now consider all intermediate vertices uptil n,
for(k=0;k<n;k++) {
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
if(graph[i][k]+graph[k][j]<graph[i][j]) {
shortdist[i][j]=graph[i][k]+graph[k][j];
}
}
}
}
print(shortdist);
}
int print(int shortdist[n][n]) {
int i,j;
cout<<”The following elements show the shortest distance b/w the respective vertices: “ <<endl;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
if(shortdist[i][j]==INF) cout<<” INF ”;
else cout<<” “<<shortdist[i][j]<<” “;
}
cout<<endl;
}
}
int main() {
int graph[n][n]={ {0 , 3 , INF , 10},
{INF , 0 , 5 , INF},
{INF , INF , 0 , 7},
{INF , INF , INF , 0}};
fwgraph(graph);
return 0;
}
/*The output given by this will be:
The following elements show the shortest distance b/w the respective vertices:
0 3 8 10
INF 0 5 12
INF INF 0 7
INF INF INF 0*/