-
Notifications
You must be signed in to change notification settings - Fork 47
/
Floyd_Warshall.cpp
85 lines (60 loc) · 1.36 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<bits/stdc++.h>
using namespace std;
typedef vector<vector<int>> vv;
#define INF INT_MAX;
int p[1000][1000];
int d[1000][1000];
void shortestPath(int i, int j){
if(i != j)
shortestPath(i, p[i][j]);
cout<<j+1<<" ";
return ;
}
void display(int n){
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
if(d[i][j] == INT_MAX)
cout<<"X ";
else
cout<<d[i][j]<<" ";
}
cout<<endl;
}
}
void floydWarshall(vv &g, int n, int src, int des){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
d[i][j] = g[i][j];
if(g[i][j] == 0 || g[i][j] == INT_MAX){
p[i][j] = INT_MAX;
}else{
p[i][j] = i;
}
}
}
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(d[i][k] != INT_MAX && g[k][j] != INT_MAX && d[i][j] > (d[i][k] + d[k][j])){
d[i][j] = d[i][k] + d[k][j];
p[i][j] = d[k][j];
}
}
}
cout<<"Pass "<<k+1<<" : \n";
display(n);
cout<<"\n";
}
cout<<"\n\n";
cout<<"The shortest path between "<<src+1<<" and "<<des+1<<" is : \n";
shortestPath(src,des);
cout<<"\nThe Distance is : "<<d[src][des];
}
int main(){
int n = 4;
vv g = { { 0, 10, 5, 3 },
{ 1, 0, INT_MAX, INT_MAX },
{ INT_MAX, 2, 0, INT_MAX },
{ INT_MAX, INT_MAX, 2, 0 } };
floydWarshall(g,n,0,1);
}