forked from AggHim/SRIB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstraAlgorithm.cpp
70 lines (66 loc) · 1.85 KB
/
DijkstraAlgorithm.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
63
64
65
66
67
68
69
70
/*
Initially weights for all vertices will be marked as Infinity, now there will be a visited array to keep track
of the vertices that are visited. We chose vertex with minimum weight from the unvisited and explore all it's neighbours
that are also unvisited and update their weights and parents if distance is lower than current weight.
*/
#include <iostream>
#include <climits>
using namespace std;
int getMin(int* distance, bool* visited, int n){
int minIndex = -1;
for(int i=0;i<n;i++){
if(visited[i]==false){
if(minIndex==-1 || distance[i]<distance[minIndex]){
minIndex = i;
}
}
}
return minIndex;
}
void dijkstra(int** graph, int n){
bool* visited = new bool[n];
int* distance = new int[n];
int* parent = new int[n];
for(int i=0;i<n;i++){
distance[i] = INT_MAX;
visited[i] = false;
parent[i] = -1;
}
distance[0] = 0;
for(int i=0;i<n-1;i++){
int minVertex = getMin(distance,visited,n);
visited[minVertex]=true;
for(int j=0;j<n;j++){
if(graph[minVertex][j]!=0 && visited[j]==false){
int d = distance[minVertex]+graph[i][j];
if(d < distance[j]){
distance[j] = d;
parent[j] = minVertex;
}
}
}
}
for(int i=0;i<n;i++){
cout << i << " Distance: " << distance[i] << " Parent: " << parent[i] << endl;
}
delete [] distance;
delete [] visited;
}
int main() {
int n,k;
cin >> n >> k;
int** graph = new int*[n];
for(int i=0;i<n;i++){
graph[i] = new int[n];
for(int j=0;j<n;j++){
graph[i][j]=0;
}
}
for(int i=0;i<k;i++){
int s,e,w;
cin >> s >> e >> w;
graph[s][e]=w;
graph[e][s]=w;
}
dijkstra(graph,n);
}