forked from harsimrans/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssspa.c
101 lines (88 loc) · 1.79 KB
/
ssspa.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
/******************************************
*
* single source shortest path problem
*
* Harsimran Singh
*
* Finds the shortest path from a given
* source vertex to all other vertices
*
* Also print_path function has been
* provided which provides the shortest
* path.
*
* 999999: Here signifies a very large
* value aka infinity.
******************************************/
#include<stdio.h>
int previous[10] = {-1}; // track down the path
void print_path(int vertex);
int main()
{
int cost[10][10];
int n;
int i, j, k;
printf("enter the num of nodes: ");
scanf("%d", &n);
int dist[n];
int taken[n];
for (i = 0 ; i < n; i++)
{
for (j = 0 ; j < n; j++)
{
scanf("%d", &cost[i][j]);
}
}
int source;
printf("enter the source: ");
scanf("%d", &source);
for (i = 0 ; i < n; i++)
{
dist[i] = cost[source][i];
taken[i] = 0;
}
taken[source] = 1;
for(i = 0; i < n; i++)
{
int min = 999999;
int minvertex;
//find the min
for (j = 0 ; j < n; j++)
{
if (taken[j] != 1 && dist[j] < min)
{
minvertex = j;
min = dist[j];
}
}
taken[minvertex] = 1;
//updations
for (j = 0 ; j < n; j++)
{
if (taken[j] != 1 && cost[i][minvertex] + cost[minvertex][j] < dist[j])
{
dist[j] = cost[i][minvertex] + cost[minvertex][j];
previous[j] = minvertex;
}
}
}
printf("The shortest distances of the vertex from source vertex is: \n");
for (i = 0 ; i < n; i++)
printf("%d ", dist[i]);
printf("\n");
return 0;
}
void print_path(int vertex)
{
if (previous[vertex] != -1 && vertex != 0)
{
print_path(previous[vertex]);
}
else
{
printf(" %d ", vertex);
return;
}
printf(" %d ", vertex);
}