-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdijkstra.cpp
More file actions
125 lines (106 loc) · 2.47 KB
/
Copy pathdijkstra.cpp
File metadata and controls
125 lines (106 loc) · 2.47 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
#include <iostream>
#include <limits.h>
#include <stdlib.h>
using namespace std;
#define INF (INT_MAX)
class Dijkstra
{
int **adjacencyMatrix, n;
public:
Dijkstra(int **adj, int n)
{
this->adjacencyMatrix = adj;
this->n = n;
}
//adjacencyMatrix: The adjacency matrix
//n: Number of nodes in the graph
//source: The source node (Zero based indexing)
int *dijkstra(int source)
{
int min, minAt;
//Set to keep track of selected nodes in the Minimal Spannnf Tree
bool *sptSet = new bool[n];
for (int i = 0; i < n; ++i)
sptSet[i] = false;
//Array to help select the next node and which will hold the minimum distances
int *d = new int[n];
for (int i = 0; i < n; ++i)
d[i] = INF;
//So that source node is selected first
d[source] = 0;
for (int i = 0; i < n - 1; ++i)
{
//Pick vertex with minimum key and which has not been visited
min = INF;
for (int i = 0; i < n; i++)
{
if (sptSet[i] == false && d[i] < min)
{
min = d[i];
minAt = i;
}
}
//min contains the node be to selected for insertion in MST
sptSet[minAt] = true;
//Update the key values to the weight of the selected node to its adjacent node if it is less.
for (int i = 0; i < n; ++i)
{
if (!sptSet[i]
&& (adjacencyMatrix[minAt][i] != INF)
&& (d[i] > d[minAt] + adjacencyMatrix[minAt][i]))
{
d[i] = d[minAt] + adjacencyMatrix[minAt][i];
}
}
}
delete sptSet;
return d;
}
};
class Utilities
{
static int **createArray2D(int row, int col, int init = 0)
{
int i, j;
int **arr = new int *[row];
for (i = 0; i < row; ++i)
arr[i] = new int[col];
for (i = 0; i < row; ++i)
{
for (j = 0; j < col; ++j)
{
arr[i][j] = init;
}
}
return arr;
}
public:
static void demo()
{
int n, i, edges, from, to, source, dist;
cout << "\nEnter number of nodes in the graph: ";
cin >> n;
int **graph = createArray2D(n, n, INF);
cout << "\nEnter the number of edges: ";
cin >> edges;
cout << "Enter edges (from - to - distance):\n";
for (i = 0; i < edges; ++i)
{
cin >> from >> to >> dist;
graph[from][to] = graph[to][from] = dist;
}
cout << "Enter the source node (Zero based indexing): ";
cin >> source;
Dijkstra *d = new Dijkstra(graph, n);
int *minDist = d->dijkstra(source);
cout << "The distance to all the notes from " << source << endl;
for (i = 0; i < n; ++i)
{
cout << source << " - " << i << '\t' << minDist[i] << endl;
}
}
};
int main()
{
Utilities::demo();
}