-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras.cpp
More file actions
69 lines (68 loc) · 1.58 KB
/
dijkstras.cpp
File metadata and controls
69 lines (68 loc) · 1.58 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
#include<iostream>
#include<stdlib.h>
#include<math.h>
int **graph;
using namespace std;
int findminvertex(int *distance,bool *visited,int n)
{
int minvertex=-1;
for(int i=0;i<n;i++)
{
if(!(visited[i])&&(minvertex==-1||distance[i]<distance[minvertex]))
minvertex=i;
}
return minvertex;
}
void dijkstras(int n,int sv)
{
bool *visited=new bool[n];
int *distance=new int[n];
for(int i=0;i<n;i++)
{
visited[i]=false;
distance[i]=INT_MAX;
}
distance[sv]=0;
for(int i=0;i<n-1;i++)
{
int minvertex=findminvertex(distance,visited,n);
visited[minvertex]=true;
for(int j=0;j<n;j++)
{
if(graph[minvertex][j]>0&&!(visited[j]))
{
int newdist=distance[minvertex]+graph[minvertex][j];
if(newdist<distance[j])
distance[j]=newdist;
}
}
}
cout<<"Shortest distances:"<<endl;
for(int i=0;i<n;i++)
cout<<distance[i]<<" ";
}
int main()
{
int n,e;
cout<<"Enter the number of vertices:";
cin>>n;
cout<<"Enter the number of edges:";
cin>>e;
int sv;
cout<<"Enter the starting vertex:";
cin>>sv;
graph=new int *[n];
for(int i=0;i<n;i++)
graph[i]=new int[n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
graph[i][j]=0;
for(int i=0;i<e;i++)
{
int s,d,w;
cin>>s>>d>>w;
graph[s][d]=w;
graph[d][s]=w;
}
dijkstras(n,sv);
}