-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra_array.cpp
More file actions
158 lines (116 loc) · 2.81 KB
/
dijkstra_array.cpp
File metadata and controls
158 lines (116 loc) · 2.81 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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <climits>
#include <iostream>
#include<stdlib.h>
#define MAX 100
#define v 100
using namespace std;
int flag;
struct node
{
bool includeset;
int finaldist;
int pred;
};
struct node nodearray[v];
/*int dijkstra(int * ,int ,int);
int initialize_single_source(struct node *,int,int);
int extract_min(struct node * ,int);*/
int initialize_single_source(struct node nodearray[],int source,int vertices)
{
for(int i=0; i<vertices; i++)
{
nodearray[i].includeset=false;
nodearray[i].pred=INT_MIN;
nodearray[i].finaldist=INT_MAX;
}
flag=vertices;
nodearray[source].pred=-1;
nodearray[source].finaldist=0;
return flag;
}
int extract_min(struct node nodearray[],int vertices)
{
int mindist, x;
for(x=0;x<vertices;x++){
if(nodearray[x].includeset==false)
{
break;
}
}
mindist=x;
for(int i=x+1;i<vertices;i++){
if(nodearray[i].includeset==false && nodearray[i].finaldist<nodearray[mindist].finaldist)
{
mindist=i;
}
}
return mindist;
}
void dijkstra(int arrk[v][v],int source,int vertices)
{
flag=initialize_single_source(nodearray,source,vertices);
int count = 0;
while( flag!=0)
{
int p=extract_min(nodearray,vertices);
nodearray[p].includeset=true;
flag--;
count++;
for(int j=1;j<vertices;j++)
{
if(arrk[p][j]!=0)
{
if(nodearray[j].finaldist> nodearray[p].finaldist + arrk[p][j])
{
nodearray[j].finaldist = nodearray[p].finaldist + arrk[p][j];
nodearray[j].pred = p;
}
}
}
}
cout<<"vertex"<<"\t\t\t"<<"Minimum distance"<<endl;
for(int i=0;i<vertices;i++)
{
cout<<i<<"\t\t\t";
cout<<nodearray[i].finaldist<<endl;
}
}
int main()
{
int i=0;
int so;
int vp;
int arrk[MAX][MAX],e;
cout<<"enter the number of vertices(undirected graph)"<<endl;
cin>>vp;
cout<<"enter the number of edges"<<endl;
cin>>e;
if(vp<=0 || e<=0)
{
cout<<"\ninvalid input";
return 0;
}
for(int i=0; i<vp; i++)
{
for(int j=0; j<vp; j++)
{
if(i!=j){
cout<<"Enter the edge length between "<<i<<" and "<<j<<" ";
cin>>arrk[i][j];}
else arrk[i][j]=0;
}
}
cout<<"output matrix is ---->"<<endl;
for(i=0; i<vp; i++)
{
for(int j=0; j<vp; j++)
{
cout<<"\t"<<arrk[i][j];
}
cout<<endl;
}
cout<<"enter source";
cin>>so;
dijkstra(arrk,so,vp);
return 0;
}