File tree 1 file changed +88
-0
lines changed
1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ #define INF INT_MAX
3
+ #define ll long long
4
+ #define N 100
5
+ using namespace std ;
6
+
7
+ ll dist[N][N], path[N][N];
8
+
9
+ void printPath (ll i, ll j) {
10
+ // cout<<"Printing path from "<<i<<" to "<<j<<endl;
11
+ stack<ll> stk;
12
+ stk.push (j);
13
+ while (path[i][j] != i && path[i][j] != -1 ) {
14
+ stk.push (path[i][j]);
15
+ j = path[i][j];
16
+ }
17
+ if (path[i][j] == -1 ) {
18
+ cout<<" No path exists\n " ;
19
+ }
20
+ else {
21
+ stk.push (i);
22
+ while (!stk.empty ()) {
23
+ cout<<stk.top ()<<" " ;
24
+ stk.pop ();
25
+ }
26
+ cout<<" \n " ;
27
+ }
28
+ }
29
+
30
+ int main () {
31
+ ll i,j,k,n,e,u,v,w;
32
+ cin>>n>>e;
33
+ for (i=0 ; i<=n; i++) {
34
+ for (j=0 ; j<=n; j++) {
35
+ if (i==j) {
36
+ dist[i][j] = 0 ;
37
+ path[i][j] = i;
38
+ }
39
+ else {
40
+ dist[i][j] = INF;
41
+ path[i][j] = -1 ;
42
+
43
+ }
44
+ }
45
+ }
46
+
47
+ for (i=0 ; i<e; i++) {
48
+ cin>>u>>v>>w;
49
+ dist[u][v] = w;
50
+ // dist[v][u] = w; //uncomment for undirected graph
51
+ path[u][v] = u;
52
+ }
53
+
54
+ for (k=1 ; k<=n; k++) {
55
+ for (i=1 ; i<=n; i++) {
56
+ for (j=1 ; j<=n; j++) {
57
+ if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
58
+ dist[i][j] = dist[i][k] + dist[k][j];
59
+ path[i][j] = path[k][j];
60
+ // cout<<i<<" ---> "<<k<<" ---> "<<j<<" dist = "<<dist[i][j]<<endl;
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ cout<<" Distance Matrix\n " ;
67
+ for (i=1 ; i<=n; i++) {
68
+ for (j=1 ; j<=n; j++) {
69
+ if (dist[i][j] == INF)
70
+ cout<<" INF " ;
71
+ else
72
+ cout<<dist[i][j]<<" " ;
73
+ }
74
+ cout<<endl;
75
+ }
76
+ cout<<" Path Matrix\n " ;
77
+ for (i=1 ; i<=n; i++) {
78
+ for (j=1 ; j<=n; j++) {
79
+ cout<<path[i][j]<<" " ;
80
+ }
81
+ cout<<endl;
82
+ }
83
+ for (i=1 ; i<=n; i++) {
84
+ for (j=1 ; j<=n; j++)
85
+ printPath (i,j);
86
+ }
87
+ return 0 ;
88
+ }
You can’t perform that action at this time.
0 commit comments