Repository navigation
Expand file tree
/
Copy pathdijkstra.c
More file actions
92 lines (78 loc) · 1.4 KB
/
Copy pathdijkstra.c
File metadata and controls
92 lines (78 loc) · 1.4 KB
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
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int v;
int minkey(int dist[],int spset[]){
int min=INT_MAX,min_index;
for(int count=0;count<v;count++){
if(spset[count]==0 && dist[count]<min){
min=dist[count];
min_index=count;
}
}
return min_index;
}
void dijkstra(int graph[][v],int source){
int dist[v];
int parent[v];
int spset[v];
for(int i=0;i<v;i++)
{
dist[i]=INT_MAX;
parent[i]=-1;
spset[i]=0;
}
dist[source]=0;
parent[source]=-1;
for(int count=0;count<v-1;count++){
int u=minkey(dist,spset);
spset[u]=1;
for(int j=0;j<v;j++){
if(spset[j]==0 && graph[u][j] && dist[u] !=INT_MAX && dist[u]+graph[u][j]<dist[j])
{
dist[j]=dist[u]+graph[u][j];
parent[j]=u;
}
}
}
printgraph(dist);
}
void printgraph(int dist[]){
printf("vertex \t Dist from source\n");
for(int i=1;i<v;i++)
{
//sum+=graph[i][parent[i]];
printf("%d \t %d\n",i,dist[i]);
}
}
int main(int argc,char* argv[]){
if(argc<2){
printf("give the file that consists of input\n");
return 1;
}
FILE* fp= fopen(argv[1],"r");
if(fp==NULL){
printf("file doesnot exists\n");
return 1;
}
if(fscanf(fp,"%d",&v)==0){
printf("error while reading number of vertices\n");
return 1;
}
//reading is completed
int graph[v][v];
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
fscanf(fp,"%d",&graph[i][j]);
}
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
printf("%d ",graph[i][j]);
printf("\n");
}
int root=0;
dijkstra(graph,root);
return 0;
}