-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkistraalgorithm.cpp
62 lines (62 loc) · 1.05 KB
/
dijkistraalgorithm.cpp
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
/*Shaik Abbu*/
#include<iostream>
using namespace std;
#define I 32467
int cost[10][10];
int dist[20]={I};
void Dijkistra(int s,int n)
{
int i,j,u,v,min=I,cnt=1;
int vis[n+1]={0};
for(int i=1;i<=n;i++)
{
dist[i]=cost[s][i];
}
vis[s]=1;
dist[s]=0;
while(cnt<=n)
{
min=I;
for(int i=1;i<=n;i++)
{
if(vis[i]==0 && dist[i]<min)
{
min=dist[i];
v=i;
}
}
vis[v]=1;
for(j=1;j<=n;j++)
{
if(!vis[j] &&cost[v][j]!=I && dist[j]>dist[v]+cost[v][j])
dist[j]=dist[v]+cost[v][j];
}
++cnt;
}
}
int main()
{
int n;
cout<<"Enter no.of vertices ";
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=I;
}
}
int s;
cout<<"Enter source : ";
cin>>s;
Dijkistra(s,n);
cout<<"The Single Sources shortest path is : ";
cout<<"\n";
for(int i=1;i<=n;i++)
{
cout<<"("<<s<<" "<<i<<")"<<"-->"<<dist[i]<<"\n";
}
return 0;
}