-
Notifications
You must be signed in to change notification settings - Fork 0
/
dij.c
65 lines (50 loc) · 1.21 KB
/
dij.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
#include <stdio.h>
int s[20], d[20];
void dij(int cost[10][10], int n, int src) {
int i, u, min, ct;
for (i = 1; i <= n; i++) {
s[i] = 0;
d[i] = cost[src][i];
}
s[src] = 1;
ct = 1;
while (ct < n) {
min = 999;
for (i = 1; i <= n; i++) {
if (d[i] < min && s[i] == 0) {
min = d[i];
u = i;
}
}
s[u] = 1;
ct++;
for (i = 1; i <= n; i++) {
if (!s[i] && (d[u] + cost[u][i] < d[i])) {
d[i] = d[u] + cost[u][i];
}
}
}
}
void main() {
int cost[10][10], n, i, j, src;
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
printf("\nEnter the cost matrix:\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0) {
cost[i][j] = 999;
}
}
}
printf("\nEnter the source node: ");
scanf("%d", &src);
dij(cost, n, src);
printf("\nShortest path:\n");
for (i = 1; i <= n; i++) {
if (i != src) {
printf("\n%d -> %d, cost = %d", src, i, d[i]);
}
}
}