-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7_all_pair_shortest_path.cpp
More file actions
81 lines (75 loc) · 1.9 KB
/
7_all_pair_shortest_path.cpp
File metadata and controls
81 lines (75 loc) · 1.9 KB
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
#include<bits/stdc++.h>
using namespace std;
#define INF 9999
int dist[4][4];
int cost[4][4] = //given cost matrix
{
{ 0,7,INF,8},
{ 10,0,6,15},
{ INF,INF,0,12},
{ 9,INF,INF,0}
};
int next_m[4][4];
int V=4;
void printPath(int i,int j) //to print path from i to j
{
if (j==next_m[i][j]) //no intermediate vertices
cout<<i<<" "<<j;
else{
cout<<i<<" ";
printPath(next_m[i][j],j);
}
}
int main()
{
int i,j,k;
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
{
dist[i][j]=cost[i][j]; //Initialize the solution matrix same as input graph matrix.
next_m[i][j]=j; //Initialize the next matrix to j (no intermediate verteies).
}
}
for(k=0;k<V;k++)
{
for(i=0;i<V;i++) // Pick all vertices as source one by one
{
for(j=0;j<V;j++) // Pick all vertices as destination for the above picked source
{
if(dist[i][k] + dist[k][j] < dist[i][j]) //if k is on the shortest path from i to j then update the value of dist[][] and next[][]
{
dist[i][j]=dist[i][k] + dist[k][j];
next_m[i][j]=next_m[i][k];
}
}
}
}
cout<<"Matrix showing the shortest distances between every pair of vertices \n";
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][j] == INF)
cout<<"INF"<<" ";
else
cout<<dist[i][j]<<" ";
}
cout<<"\n";
}
cout<<"The predecessor matrix is:\n";
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
cout<<next_m[i][j]<<" ";
if(j==V-1)
cout<<"\n";
}
}
int a,b;
cout<<"enter the values of start and end for path to obtain:\n";
cin>>a>>b;
printPath(a,b);
return 0;
}