-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjohnsons.c
155 lines (133 loc) · 2.23 KB
/
johnsons.c
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include<stdio.h>
int A[10][10],D[10],D2[10],P[10],V,H[10],W[10][10],DW[10][10];
int bellmanford(int s);
void dijkstras(int);
void main()
{
int i,j,s;
printf("Enter the number of vertices\n");
scanf("%d",&V);
printf("Enter the weight matrix (999 for infinity):\n");
for(i=0;i<V;i++)
for(j=0;j<V;j++)
scanf("%d",&A[i][j]);
//new vertices s
s=V;
for(i=0;i<=V;i++)
A[s][i]=0;
for(i=0;i<V;i++)
A[i][s]=999;
V=V+1;
if(!bellmanford(s))
{
printf("The graph contains negative cycles\n");
}
else
{
/*printf("The shortes path are as follows:\n");
for(i=0;i<V;i++)
{
printf("D[%d]=%d\n",i,D[i]);
printf("P[%d]=%d\n",i,P[i]);
}*/
V=V-1;
for(i=0;i<V;i++)
for(j=0;j<V;j++)
{
if(A[i][j]!=999)
W[i][j]=A[i][j]+D[i]-D[j];
else
W[i][j]=999;
}
/* printf("The distance matrix W is:\n");
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
printf("%d\t",W[i][j]) ;
printf("\n");
}
printf("The distance matrix D is:\n");
for(i=0;i<V;i++)
printf("%d\t",D[i]);
printf("\n");
*/
for(i=0;i<V;i++)
{
dijkstras(i);
for(j=0;j<V;j++)
{
DW[i][j]=D2[j]+D[j]-D[i];
}
}
printf("The distance matrix is:\n");
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
printf("%d\t",DW[i][j]) ;
printf("\n");
}
}
}
int bellmanford(int s)
{
int i,j,k;
for(i=0;i<V;i++)
{
D[i]=999;
P[i]=i;
}
D[s]=0;
for(k=0;k<V-1;k++)
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
{
if(A[i][j]!=999)
{
if((D[i]+A[i][j])<D[j])
{
D[j]=D[i]+A[i][j];
P[j]=i;
}
}
}
}
for(i=0;i<V;i++)
for(j=0;j<V;j++)
if((D[i]+A[i][j])<D[j])
{
return 0;
}
return 1;
}
void dijkstras(int s)
{
int i,j,flag[10],count=1,min,u;
for(i=0;i<V;i++)
{
D2[i]=W[s][i];
flag[i]=0;
}
D2[s]=0;
flag[s]=1;
while(count<V)
{
min=999;
for(i=0;i<V;i++)
if(D2[i]<min && !flag[i])
{
min= D2[i];
u=i;
}
flag[u]=1;
count++;
for(i=0;i<V;i++)
if(D2[u]+W[u][i]<D2[i] && !flag[i])
{
D2[i]=D2[u]+W[u][i];
}
}
/* for(i=0;i<V;i++)
printf("%d\t",D2[i]);
printf("\n");*/
}