-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dj2.c
129 lines (124 loc) · 2.91 KB
/
Dj2.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
//Djikstra algorithm
#include<stdio.h>
#include<conio.h>
#define MAX 10
struct table
{
int known[MAX];
int dist[MAX];
int pv[MAX];
}T;
struct graph
{
int matrix[MAX][MAX];
int n;
}G;
void readgraph()
{
int i,j,u,v,cost,ch=1;
printf("\nEnter no. of vertices:");
scanf("%d",&G.n);
for(i=0;i<G.n;i++)
for(j=0;j<G.n;j++)
G.matrix[i][j]=0;
while(ch==1)
{
printf("enter the first vertex ");
scanf("%d",&u);
printf("enter the next vertex ");
scanf("%d",&v);
printf("enter the cost ");
scanf("%d",&cost);
G.matrix[u-1][v-1]=cost;
printf("\ndo you want to enter another edge (1-yes 2-no)");
scanf("%d",&ch);
}
}
void displaymat()
{
int i,j;
for(i=0;i<G.n;i++)
printf("\tV %d",i+1);
printf("\n\n");
for( i=0;i<G.n;i++)
{
printf("V %d",i+1);
printf("\t");
for(j=0;j<G.n;j++)
{
printf("%d",G.matrix[i][j]);
printf("\t");
}
printf("\n");
}
}
void inittable()
{
int i;
for(i=0;i<G.n;i++)
{
T.known[i]=0;
T.dist[i]=999;
T.pv[i]=0;
}
}
int smallest()
{
int i,min=999,index=-1;
for(i=0;i<G.n;i++)
{
if(T.known[i]==0 && T.dist[i]<min)
{
min=T.dist[i];
index=i;
}
}
return index;
}
void displaytable()
{
int i;
printf("\nVertex Known distance previous\n");
for(i=0;i<G.n;i++)
{
printf("\n\nV %d \t %d \t %d \t %d",i+1,T.known[i], T.dist[i], T.pv[i]);
}
}
void dj(int start)
{
int i,j,small=start-1;
T.dist[start-1]=0;
for(;;)
{
printf("hi");
T.known[small]=1;
displaytable();
for(j=0;j<G.n;j++)
{
if(T.known[j]==0 && G.matrix[small][j]!=0)
if(T.dist[small] + G.matrix[small][j] < T.dist[j])
{
T.pv[j]=small+1;
T.dist[j]=T.dist[small] + G.matrix[small][j];
}
}
small=smallest();
if(small==-1)
break;
}
}
int main()
{
int start;
printf("\nDIJKSTRA ALGORITHM");
readgraph();
displaymat();
inittable();
printf("\nEnter the starting Vertex:");
scanf("%d",&start);
dj(start);
printf("\nfinal:");
displaytable();
getch();
return 0;
}