forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BreadthFirstShortestPaths.cs
303 lines (239 loc) · 10.5 KB
/
BreadthFirstShortestPaths.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/***
* Computes Shortest-Paths for Unweighted Graphs using the Breadth-First Search algorithm.
* It provides the capability to find shortest-paths from a single-source and multiple-sources, in addition to looking up reachable and unreachable nodes.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Algorithms.Common;
using DataStructures.Graphs;
namespace Algorithms.Graphs
{
public class BreadthFirstShortestPaths<T> where T : IComparable<T>
{
private int _edgesCount { get; set; }
private int _verticesCount { get; set; }
private bool[] _visited { get; set; }
private Int64[] _distances { get; set; }
private int[] _predecessors { get; set; }
// A dictionary that maps node-values to integer indeces
private Dictionary<T, int> _nodesToIndices { get; set; }
// A dictionary that maps integer index to node-value
private Dictionary<int, T> _indicesToNodes { get; set; }
// A const that represent an infinite distance
private const Int64 INFINITY = Int64.MaxValue;
/// <summary>
/// CONSTRUCTOR.
/// Breadth First Searcher from Single Source.
/// </summary>
public BreadthFirstShortestPaths(IGraph<T> Graph, T Source)
{
if (Graph == null)
throw new ArgumentNullException();
if (!Graph.HasVertex(Source))
throw new ArgumentException("The source vertex doesn't belong to graph.");
// Init
_initializeDataMembers(Graph);
// Single source BFS
_breadthFirstSearch(Graph, Source);
//bool optimalityConditionsSatisfied = checkOptimalityConditions (Graph, Source);
Debug.Assert(checkOptimalityConditions(Graph, Source));
}
/// <summary>
/// CONSTRUCTOR.
/// Breadth First Searcher from Multiple Sources.
/// </summary>
public BreadthFirstShortestPaths(IGraph<T> Graph, IList<T> Sources)
{
if (Graph == null)
throw new ArgumentNullException();
if (Sources == null || Sources.Count == 0)
throw new ArgumentException("Sources list is either null or empty.");
// Init
_initializeDataMembers(Graph);
// Multiple sources BFS
_breadthFirstSearch(Graph, Sources);
}
/************************************************************************************************************/
/// <summary>
/// Constructors helper function. Initializes some of the data memebers.
/// </summary>
private void _initializeDataMembers(IGraph<T> Graph)
{
_edgesCount = Graph.EdgesCount;
_verticesCount = Graph.VerticesCount;
_visited = new bool[_verticesCount];
_distances = new Int64[_verticesCount];
_predecessors = new int[_verticesCount];
_nodesToIndices = new Dictionary<T, int>();
_indicesToNodes = new Dictionary<int, T>();
// Reset the visited, distances and predeccessors arrays
int i = 0;
foreach (var node in Graph.Vertices)
{
if (i >= _verticesCount)
break;
_visited[i] = false;
_distances[i] = INFINITY;
_predecessors[i] = -1;
_nodesToIndices.Add(node, i);
_indicesToNodes.Add(i, node);
++i;
}
}
/// <summary>
/// Privat helper. Breadth First Search from Single Source.
/// </summary>
private void _breadthFirstSearch(IGraph<T> graph, T source)
{
// Set distance to current to zero
_distances[_nodesToIndices[source]] = 0;
// Set current to visited: true.
_visited[_nodesToIndices[source]] = true;
var queue = new Queue<T>(_verticesCount);
queue.Enqueue(source);
while (queue.Count > 0)
{
var current = queue.Dequeue();
int indexOfCurrent = _nodesToIndices[current];
foreach (var adjacent in graph.Neighbours(current))
{
int indexOfAdjacent = _nodesToIndices[adjacent];
if (!_visited[indexOfAdjacent])
{
_predecessors[indexOfAdjacent] = indexOfCurrent;
_distances[indexOfAdjacent] = _distances[indexOfCurrent] + 1;
_visited[indexOfAdjacent] = true;
queue.Enqueue(adjacent);
}
}//end-foreach
}//end-while
}
/// <summary>
/// Privat helper. Breadth First Search from Multiple Sources.
/// </summary>
private void _breadthFirstSearch(IGraph<T> graph, IList<T> sources)
{
// Define helper variables.
var queue = new Queue<T>(_verticesCount);
foreach (var source in sources)
{
if (!graph.HasVertex(source))
throw new Exception("Graph doesn't has a vertex '" + source + "'");
int index = _nodesToIndices[source];
_distances[index] = 0;
_visited[index] = true;
queue.Enqueue(source);
}
while (queue.Count > 0)
{
var current = queue.Dequeue();
int indexOfCurrent = _nodesToIndices[current];
foreach (var adjacent in graph.Neighbours(current))
{
int indexOfAdjacent = _nodesToIndices[adjacent];
if (!_visited[indexOfAdjacent])
{
_predecessors[indexOfAdjacent] = indexOfCurrent;
_distances[indexOfAdjacent] = _distances[indexOfCurrent] + 1;
_visited[indexOfAdjacent] = true;
queue.Enqueue(adjacent);
}
}//end-foreach
}//end-while
}
/// <summary>
/// Private helper. Checks optimality conditions for single source
/// </summary>
private bool checkOptimalityConditions(IGraph<T> graph, T source)
{
int indexOfSource = _nodesToIndices[source];
// check that the distance of s = 0
if (_distances[indexOfSource] != 0)
{
Console.WriteLine("Distance of source '" + source + "' to itself = " + _distances[indexOfSource]);
return false;
}
// check that for each edge v-w dist[w] <= dist[v] + 1
// provided v is reachable from s
foreach (var node in graph.Vertices)
{
int v = _nodesToIndices[node];
foreach (var adjacent in graph.Neighbours(node))
{
int w = _nodesToIndices[adjacent];
if (HasPathTo(node) != HasPathTo(adjacent))
{
Console.WriteLine("edge " + node + "-" + adjacent);
Console.WriteLine("hasPathTo(" + node + ") = " + HasPathTo(node));
Console.WriteLine("hasPathTo(" + adjacent + ") = " + HasPathTo(adjacent));
return false;
}
if (HasPathTo(node) && (_distances[w] > _distances[v] + 1))
{
Console.WriteLine("edge " + node + "-" + adjacent);
Console.WriteLine("distanceTo[" + node + "] = " + _distances[v]);
Console.WriteLine("distanceTo[" + adjacent + "] = " + _distances[w]);
return false;
}
}
}
// check that v = edgeTo[w] satisfies distTo[w] + distTo[v] + 1
// provided v is reachable from source
foreach (var node in graph.Vertices)
{
int w = _nodesToIndices[node];
if (!HasPathTo(node) || node.IsEqualTo(source))
continue;
int v = _predecessors[w];
if (_distances[w] != _distances[v] + 1)
{
Console.WriteLine("shortest path edge " + v + "-" + w);
Console.WriteLine("distanceTo[" + v + "] = " + _distances[v]);
Console.WriteLine("distanceTo[" + w + "] = " + _distances[w]);
return false;
}
}
return true;
}
/************************************************************************************************************/
/// <summary>
/// Determines whether there is a path from the source vertex to this specified vertex.
/// </summary>
public bool HasPathTo(T destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
int dstIndex = _nodesToIndices[destination];
return (_visited[dstIndex]);
}
/// <summary>
/// Returns the distance between the source vertex and the specified vertex.
/// </summary>
public long DistanceTo(T destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
int dstIndex = _nodesToIndices[destination];
return (_distances[dstIndex]);
}
/// <summary>
/// Returns an enumerable collection of nodes that specify the shortest path from the source vertex to the destination vertex.
/// </summary>
public IEnumerable<T> ShortestPathTo(T destination)
{
if (!_nodesToIndices.ContainsKey(destination))
throw new Exception("Graph doesn't have the specified vertex.");
if (!HasPathTo(destination))
return null;
int dstIndex = _nodesToIndices[destination];
var stack = new DataStructures.Lists.Stack<T>();
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;
}
}
}