forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DijkstraShortestPaths.cs
278 lines (222 loc) · 9.94 KB
/
DijkstraShortestPaths.cs
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/***
* Computes Dijkstra's Shortest-Paths for Directed Weighted Graphs from a single-source to all destinations.
* This class provides the same API as the BreadthFirstShortestPaths<T>.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Algorithms.Common;
using DataStructures.Graphs;
using DataStructures.Heaps;
namespace Algorithms.Graphs
{
public class DijkstraShortestPaths<TGraph, TVertex>
where TGraph : IGraph<TVertex>, IWeightedGraph<TVertex>
where TVertex : IComparable<TVertex>
{
/// <summary>
/// INSTANCE VARIABLES
/// </summary>
private int _edgesCount;
private int _verticesCount;
private long[] _distances;
private int[] _predecessors;
private WeightedEdge<TVertex>[] _edgeTo;
// A dictionary that maps node-values to integer indeces
private Dictionary<TVertex, int> _nodesToIndices;
// A dictionary that maps integer index to node-value
private Dictionary<int, TVertex> _indicesToNodes;
// A const that represent an infinite distance
private const Int64 Infinity = Int64.MaxValue;
private const int NilPredecessor = -1;
/// <summary>
/// CONSTRUCTOR
/// </summary>
/// <param name="Graph"></param>
public DijkstraShortestPaths(TGraph Graph, TVertex Source)
{
if (Graph == null)
throw new ArgumentNullException();
else if (!Graph.HasVertex(Source))
throw new ArgumentException("The source vertex doesn't belong to graph.");
// Init
_initializeDataMembers(Graph);
// Traverse the graph
_dijkstra(Graph, Source);
// check for the acyclic invariant
//if (!_checkOptimalityConditions(Graph, Source))
// throw new Exception("Graph doesn't match optimality conditions.");
Debug.Assert(_checkOptimalityConditions(Graph, Source));
}
/************************************************************************************************************/
/// <summary>
/// The Dijkstra's algorithm.
/// </summary>
private void _dijkstra(TGraph graph, TVertex source)
{
var minPQ = new MinPriorityQueue<TVertex, long>((uint)_verticesCount);
int srcIndex = _nodesToIndices[source];
_distances[srcIndex] = 0;
minPQ.Enqueue(source, _distances[srcIndex]);
// Main loop
while (!minPQ.IsEmpty)
{
var current = minPQ.DequeueMin(); // get vertex with min weight
var currentIndex = _nodesToIndices[current]; // get its index
var edges = graph.OutgoingEdges(current) as IEnumerable<WeightedEdge<TVertex>>; // get its outgoing weighted edges
foreach (var edge in edges)
{
var adjacentIndex = _nodesToIndices[edge.Destination];
// calculate a new possible weighted path if the edge weight is less than infinity
var delta = Infinity;
if (edge.Weight < Infinity && (Infinity - edge.Weight) > _distances[currentIndex]) // Handles overflow
delta = _distances[currentIndex] + edge.Weight;
// Relax the edge
// if check is true, a shorter path is found from current to adjacent
if (delta < _distances[adjacentIndex])
{
_edgeTo[adjacentIndex] = edge;
_distances[adjacentIndex] = delta;
_predecessors[adjacentIndex] = currentIndex;
// decrease priority with a new distance if it exists; otherwise enqueque it
if (minPQ.Contains(edge.Destination))
minPQ.UpdatePriority(edge.Destination, delta);
else
minPQ.Enqueue(edge.Destination, delta);
}
}//end-foreach
}//end-while
}
/// <summary>
/// Constructors helper function. Initializes some of the data memebers.
/// </summary>
private void _initializeDataMembers(TGraph Graph)
{
_edgesCount = Graph.EdgesCount;
_verticesCount = Graph.VerticesCount;
_distances = new Int64[_verticesCount];
_predecessors = new int[_verticesCount];
_edgeTo = new WeightedEdge<TVertex>[_edgesCount];
_nodesToIndices = new Dictionary<TVertex, int>();
_indicesToNodes = new Dictionary<int, TVertex>();
// Reset the information arrays
int i = 0;
foreach (var node in Graph.Vertices)
{
if (i >= _verticesCount)
break;
_edgeTo[i] = null;
_distances[i] = Infinity;
_predecessors[i] = NilPredecessor;
_nodesToIndices.Add(node, i);
_indicesToNodes.Add(i, node);
++i;
}
}
/// <summary>
/// Constructors helper function. Checks Optimality Conditions:
/// (i) for all edges e: distTo[e.to()] <= distTo[e.from()] + e.weight()
/// (ii) for all edge e on the SPT: distTo[e.to()] == distTo[e.from()] + e.weight()
/// </summary>
private bool _checkOptimalityConditions(TGraph graph, TVertex source)
{
// Get the source index (to be used with the information arrays).
int s = _nodesToIndices[source];
// check that edge weights are nonnegative
foreach (var edge in graph.Edges)
{
if (edge.Weight < 0)
{
Console.WriteLine("Negative edge weight detected.");
return false;
}
}
// check that distTo[v] and edgeTo[v] are consistent
if (_distances[s] != 0 || _predecessors[s] != NilPredecessor)
{
Console.WriteLine("distanceTo[s] and edgeTo[s] are inconsistent");
return false;
}
for (int v = 0; v < graph.VerticesCount; v++)
{
if (v == s)
continue;
if (_predecessors[v] == NilPredecessor && _distances[v] != Infinity)
{
Console.WriteLine("distanceTo[] and edgeTo[] are inconsistent for at least one vertex.");
return false;
}
}
// check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight()
foreach (var vertex in graph.Vertices)
{
int v = _nodesToIndices[vertex];
foreach (var edge in graph.NeighboursMap(vertex))
{
int w = _nodesToIndices[edge.Key];
if (_distances[v] + edge.Value < _distances[w])
{
Console.WriteLine("edge " + vertex + "-" + edge.Key + " is not relaxed");
return false;
}
}
}
// check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight()
foreach (var vertex in graph.Vertices)
{
int w = _nodesToIndices[vertex];
if (_edgeTo[w] == null)
continue;
var edge = _edgeTo[w];
int v = _nodesToIndices[edge.Source];
if (!vertex.IsEqualTo(edge.Destination))
return false;
if ((_distances[v] + edge.Weight) != _distances[w])
{
Console.WriteLine("edge " + edge.Source + "-" + edge.Destination + " on shortest path not tight");
return false;
}
}
return true;
}
/************************************************************************************************************/
/// <summary>
/// Determines whether there is a path from the source vertex to this specified vertex.
/// </summary>
public bool HasPathTo(TVertex destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
int index = _nodesToIndices[destination];
return _distances[index] != Infinity;
}
/// <summary>
/// Returns the distance between the source vertex and the specified vertex.
/// </summary>
public long DistanceTo(TVertex destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
int index = _nodesToIndices[destination];
return _distances[index];
}
/// <summary>
/// Returns an enumerable collection of nodes that specify the shortest path from the source vertex to the destination vertex.
/// </summary>
public IEnumerable<TVertex> ShortestPathTo(TVertex destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
else if (!HasPathTo(destination))
return null;
int dstIndex = _nodesToIndices[destination];
var stack = new DataStructures.Lists.Stack<TVertex>();
int index;
for (index = dstIndex; _distances[index] != 0; index = _predecessors[index])
stack.Push(_indicesToNodes[index]);
// Push the source vertex
stack.Push(_indicesToNodes[index]);
return stack;
}
}
}