-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.c
75 lines (70 loc) · 1.72 KB
/
15.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
#include <stdio.h>
#include <stdlib.h>
int cost[10][10], n, visited[10] = {0}, opc = 0;
int distance[10], parent[10];
void createGraph()
{
int i, j;
printf("Enter no. of vertices: ");
scanf("%d", &n);
printf("Enter Weight 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] = 1000;
}
}
}
void Dijkstra(int start)
{
int count, mindistance, nextnode, i, j;
for (i = 1; i <= n; i++)
{
distance[i] = cost[start][i];
parent[i] = start;
visited[i] = 0;
}
distance[start] = 0;
visited[start] = 1;
count = 0;
while (count < n - 1)
{
mindistance = 999;
for (i = 1; i <= n; i++)
{
opc++;
if (distance[i] < mindistance && !visited[i])
{
mindistance = distance[i];
nextnode = i;
}
}
visited[nextnode] = 1;
for (i = 1; i <= n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i])
{
distance[i] = mindistance + cost[nextnode][i];
parent[i] = nextnode;
}
count++;
}
for (i = 1; i <= n; i++)
if (i != start&&distance[i]<1000)
{
printf("%d to %d Distance : %d\n", start, i, distance[i]);
}
}
void main()
{
int source;
createGraph();
printf("Enter the source : ");
scanf("%d", &source);
printf("Minimum Distance from Source(%d) to other Vertices\n", source);
Dijkstra(source);
printf("Operation Count : %d\n", opc);
}