-
Notifications
You must be signed in to change notification settings - Fork 0
/
FloydWarshall.c
131 lines (123 loc) · 2.04 KB
/
FloydWarshall.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
#include<stdio.h>
#include<string.h>
#define INF 999
int D[10][10];
int P[10][10];
int V,E;
int G[10][10];
//Reading Graph
void readGraph()
{
int i=0,j=0;
printf("\nEnter graph in matrix form\n");
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
{
scanf("%d",&G[i][j]);
}
}
}
//Displaying graph
void displayGraph(int G[][10])
{
for(int i = 0;i<V;i++)
{
for (int j=0;j<V;j++)
printf("%d\t",G[i][j]);
printf("\n");
}
printf("\n");
}
//Initializing
void initialize()
{
for (int i = 0; i < V; i++)
{
for(int j = 0; j < V; j++)
{
if (i==j)
{
D[i][j] = 0;
P[i][j] = -1;
}
else if(G[i][j] == 0)
{
D[i][j] = INF;
P[i][j] = -1;
}
else
{
D[i][j] = G[i][j];
P[i][j] = i;
}
}
}
}
//floyd warshall
void floydwarshall()
{
int i,j,k;
for(k = 0; k < V; k++)
{
for(i = 0; i < V; i++)
{
for(j = 0; j < V; j++ )
{
if (D[i][j]<=D[i][k]+D[k][j])
continue;
else
{
D[i][j] = D[i][k]+D[k][j];
P[i][j] = P[k][j];
}
}
}
}
}
//Printing Path
void printpath(int s,int v)
{
if (v==s)
printf(" %d ",s);
else if(P[s][v] == -1)
printf("No path exist");
else
{
printpath(s,P[s][v]);
printf("-->");
printf(" %d ",v);
}
}
int main()
{
printf("\n Enter number of vertices : ");
scanf("%d",&V);
readGraph();
displayGraph(G);
initialize();
printf("\nAfter initialization...D and P matrix\n");
printf("\n D Matrix...\n");
displayGraph(D);
printf("\n P Matrix...\n");
displayGraph(P);
floydwarshall();
printf("\nAfter Floyd Warshall...D and P matrix\n");
printf("\n D Matrix...\n");
displayGraph(D);
printf("\n P Matrix...\n");
displayGraph(P);
printf("\nPrinting Path\n");
for (int i = 0; i<V ; i++)
{
for(int j =0; j<V ; j++)
{
if (i == j)
continue;
printf("path from %d to %d is ",i,j);
printpath(i,j);
printf("\n");
}
}
return 0;
}