-
Notifications
You must be signed in to change notification settings - Fork 0
/
dji_short_mine.cpp
105 lines (94 loc) · 2.53 KB
/
dji_short_mine.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
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
// C++ program to find the shortest path
// with minimum edges in a graph
#include <iostream>
using namespace std;
#define INFINITY 9999
#define n 5
#define s 0
#define d 3
#define NILL -1
int MinDistance(int*, int*);
void PrintPath(int*, int);
// Function to find the shortest path
// with minimum edges in a graph
void Dijkstra(int Graph[n][n], int _n, int _s, int _d)
{
int i, u, v, count;
int dist[n];
int Blackened[n] = { 0 };
int pathlength[n] = { 0 };
int parent[n];
// The parent Of the source vertex is always equal to nill
parent[_s] = NILL;
// first, we initialize all distances to infinity.
for (i = 0; i < n; i++)
dist[i] = INFINITY;
dist[_s] = 0;
for (count = 0; count < n - 1; count++) {
u = MinDistance(dist, Blackened);
// if MinDistance() returns INFINITY, then the graph is not
// connected and we have traversed all of the vertices in the
// connected component of the source vertex, so it can reduce
// the time complexity sometimes
// In a directed graph, it means that the source vertex
// is not a root
if (u == INFINITY)
break;
else {
// Mark the vertex as Blackened
Blackened[u] = 1;
for (v = 0; v < n; v++) {
if (!Blackened[v] && Graph[u][v]
&& dist[u] + Graph[u][v] < dist[v]) {
parent[v] = u;
pathlength[v] = pathlength[parent[v]] + 1;
dist[v] = dist[u] + Graph[u][v];
}
else if (!Blackened[v] && Graph[u][v]
&& dist[u] + Graph[u][v] == dist[v]
&& pathlength[u] + 1 < pathlength[v]) {
parent[v] = u;
pathlength[v] = pathlength[u] + 1;
}
}
}
}
// Printing the path
if (dist[_d] != INFINITY)
PrintPath(parent, _d);
else
cout << "There is no path between vertex "
<< _s << "to vertex " << _d;
}
int MinDistance(int* dist, int* Blackened)
{
int min = INFINITY, min_index, v;
for (v = 0; v < n; v++)
if (!Blackened[v] && dist[v] < min) {
min = dist[v];
min_index = v;
}
return min == INFINITY ? INFINITY : min_index;
}
// Function to print the path
void PrintPath(int* parent, int _d)
{
if (parent[_d] == NILL) {
cout << _d;
return;
}
PrintPath(parent, parent[_d]);
cout << "->" << _d;
}
// Driver code
int main()
{
// INFINITY means that u and v are not neighbors.
int Graph[n][n] = { { 0, 1, INFINITY, INFINITY, 10 },
{ 1, 0, 4, INFINITY, INFINITY },
{ INFINITY, 4, 0, 7, INFINITY },
{ INFINITY, INFINITY, 7, 0, 2 },
{ 10, INFINITY, INFINITY, 2, 0 } };
Dijkstra(Graph, n, s, d);
return 0;
}