-
Notifications
You must be signed in to change notification settings - Fork 53
/
Dijsktra.c
126 lines (124 loc) · 2.54 KB
/
Dijsktra.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
// Dijsktra algorithm in c
#include<stdio.h>
#include<stdlib.h>
#define MAX 21
#define INFINITY (int)1e9
#define TEMP 0
#define PERM 1
#define NIL -1
int adj[MAX][MAX];
int predecessor[MAX];
int pathLength[MAX];
int status[MAX];
int n;
//display
void display()
{
for(int i=0;i<=n;++i)
for(int j=0;j<=n;++j)
printf("%d ",adj[i][j]);
}
//create graph
void create_graph()
{
printf("Enter total no of nodes: ");
scanf("%d",&n);
int max_length=n*(n-1);
int u,v,w;
for(u=0,v=0;u!=-1 && v!=-1;)
{
printf("\nEnter u and v (-1 -1 to stop): ");
scanf("%d %d",&u,&v);
if(u==-1 && v==-1)
break;
printf("\nEnter weight: ");
scanf("%d",&w);
if(u>n || v>n || w<0 || u<0||v<0)
{
printf("Invalid Input");
continue;
}
adj[u][v]=w;
}
}
//min temporary satus
int min_temp_status()
{
int min=INFINITY;
int index=0;
for(int i=0;i<=n;++i)
{
if(!status[i] && pathLength[i]<min)
{
min=pathLength[i];
index=i;
}
}
return index;
}
//check status array
int check_status()//returns a boolean output
{
for(int i=0;i<=n;++i)
if(status[i]==0)
return 1;
return 0;
}
//dijkstra
void dijktra(int source)
{
for(int i=0;i<=n;++i)
{
predecessor[i]=NIL;
pathLength[i]=INFINITY;
}
status[source]=PERM;
pathLength[source]=0;
while(check_status())
{
for(int i=0;i<=n;++i)
{
if(source==i || !adj[source][i])
continue;
if(pathLength[i]>pathLength[source]+adj[source][i])
{
pathLength[i]=adj[source][i]+pathLength[source];
predecessor[i]=source;
}
}
int min= min_temp_status();
source=min;
status[min]=PERM;
}
//printf("I am successfully executed");
}
//get path
void getpath(int source,int destination)
{
int val[MAX];
int size=0;
val[size++]=destination;
while(destination!=source)
{
if(predecessor[destination]==-1)
{
printf("No path found\n");
exit(0);
}
val[size++]=predecessor[destination];
destination=predecessor[destination];
}
for(int i=size-1;i>=0;--i)
printf("%d--> ",val[i]);
}
int main()
{
int u,v;
create_graph();
//display();
printf("\nEnter source and destination: ");
scanf("%d %d",&u,&v);
dijktra(u);
getpath(u,v);
return 0;
}