- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathBreadthFirstShortestPaths.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.
*/
usingSystem;
usingSystem.Diagnostics;
usingSystem.Collections.Generic;
usingAlgorithms.Common;
usingDataStructures.Graphs;
namespaceAlgorithms.Graphs
{
publicclassBreadthFirstShortestPaths<T>whereT:IComparable<T>
{
privateint_edgesCount{get;set;}
privateint_verticesCount{get;set;}
privatebool[]_visited{get;set;}
privateInt64[]_distances{get;set;}
privateint[]_predecessors{get;set;}
// A dictionary that maps node-values to integer indeces
privateDictionary<T,int>_nodesToIndices{get;set;}
// A dictionary that maps integer index to node-value
privateDictionary<int,T>_indicesToNodes{get;set;}
// A const that represent an infinite distance
privateconstInt64INFINITY=Int64.MaxValue;
/// <summary>
/// CONSTRUCTOR.
/// Breadth First Searcher from Single Source.
/// </summary>
publicBreadthFirstShortestPaths(IGraph<T>Graph,TSource)
{
if(Graph==null)
thrownewArgumentNullException();
if(!Graph.HasVertex(Source))
thrownewArgumentException("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>
publicBreadthFirstShortestPaths(IGraph<T>Graph,IList<T>Sources)
{
if(Graph==null)
thrownewArgumentNullException();
if(Sources==null||Sources.Count==0)
thrownewArgumentException("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>
privatevoid_initializeDataMembers(IGraph<T>Graph)
{
_edgesCount=Graph.EdgesCount;
_verticesCount=Graph.VerticesCount;
_visited=newbool[_verticesCount];
_distances=newInt64[_verticesCount];
_predecessors=newint[_verticesCount];
_nodesToIndices=newDictionary<T,int>();
_indicesToNodes=newDictionary<int,T>();
// Reset the visited, distances and predeccessors arrays
inti=0;
foreach(varnodeinGraph.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>
privatevoid_breadthFirstSearch(IGraph<T>graph,Tsource)
{
// Set distance to current to zero
_distances[_nodesToIndices[source]]=0;
// Set current to visited: true.
_visited[_nodesToIndices[source]]=true;
varqueue=newQueue<T>(_verticesCount);
queue.Enqueue(source);
while(queue.Count>0)
{
varcurrent=queue.Dequeue();
intindexOfCurrent=_nodesToIndices[current];
foreach(varadjacentingraph.Neighbours(current))
{
intindexOfAdjacent=_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>
privatevoid_breadthFirstSearch(IGraph<T>graph,IList<T>sources)
{
// Define helper variables.
varqueue=newQueue<T>(_verticesCount);
foreach(varsourceinsources)
{
if(!graph.HasVertex(source))
thrownewException("Graph doesn't has a vertex '"+source+"'");
intindex=_nodesToIndices[source];
_distances[index]=0;
_visited[index]=true;
queue.Enqueue(source);
}
while(queue.Count>0)
{
varcurrent=queue.Dequeue();
intindexOfCurrent=_nodesToIndices[current];
foreach(varadjacentingraph.Neighbours(current))
{
intindexOfAdjacent=_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>
privateboolcheckOptimalityConditions(IGraph<T>graph,Tsource)
{
intindexOfSource=_nodesToIndices[source];
// check that the distance of s = 0
if(_distances[indexOfSource]!=0)
{
Console.WriteLine("Distance of source '"+source+"' to itself = "+_distances[indexOfSource]);
returnfalse;
}
// check that for each edge v-w dist[w] <= dist[v] + 1
// provided v is reachable from s
foreach(varnodeingraph.Vertices)
{
intv=_nodesToIndices[node];
foreach(varadjacentingraph.Neighbours(node))
{
intw=_nodesToIndices[adjacent];
if(HasPathTo(node)!=HasPathTo(adjacent))
{
Console.WriteLine("edge "+node+"-"+adjacent);
Console.WriteLine("hasPathTo("+node+") = "+HasPathTo(node));
Console.WriteLine("hasPathTo("+adjacent+") = "+HasPathTo(adjacent));
returnfalse;
}
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]);
returnfalse;
}
}
}
// check that v = edgeTo[w] satisfies distTo[w] + distTo[v] + 1
// provided v is reachable from source
foreach(varnodeingraph.Vertices)
{
intw=_nodesToIndices[node];
if(!HasPathTo(node)||node.IsEqualTo(source))
continue;
intv=_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]);
returnfalse;
}
}
returntrue;
}
/************************************************************************************************************/
/// <summary>
/// Determines whether there is a path from the source vertex to this specified vertex.
/// </summary>
publicboolHasPathTo(Tdestination)
{
if(!_nodesToIndices.ContainsKey(destination))
thrownewException("Graph doesn't have the specified vertex.");
intdstIndex=_nodesToIndices[destination];
return(_visited[dstIndex]);
}
/// <summary>
/// Returns the distance between the source vertex and the specified vertex.
/// </summary>
publiclongDistanceTo(Tdestination)
{
if(!_nodesToIndices.ContainsKey(destination))
thrownewException("Graph doesn't have the specified vertex.");
intdstIndex=_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>
publicIEnumerable<T>ShortestPathTo(Tdestination)
{
if(!_nodesToIndices.ContainsKey(destination))
thrownewException("Graph doesn't have the specified vertex.");
if(!HasPathTo(destination))
returnnull;
intdstIndex=_nodesToIndices[destination];
varstack=newDataStructures.Lists.Stack<T>();
intindex;
for(index=dstIndex;_distances[index]!=0;index=_predecessors[index])
stack.Push(_indicesToNodes[index]);
// Push the source vertex
stack.Push(_indicesToNodes[index]);
returnstack;
}
}
}