-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphUtils.cs
More file actions
1995 lines (1922 loc) · 87.8 KB
/
GraphUtils.cs
File metadata and controls
1995 lines (1922 loc) · 87.8 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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
// ReSharper disable UnusedMember.Global
namespace SharpAlgos
{
public class Graph<T>
{
#region Private fields
private readonly IDictionary<T, IDictionary<T, double>> _edgesWithCost = new Dictionary<T, IDictionary<T, double>>();
private readonly bool _isDirected;
#endregion
public Graph(bool isDirected) { _isDirected = isDirected; }
public void Add(T from, T to, double cost)
{
AddVertex(from);
AddVertex(to);
_edgesWithCost[from][to] = cost;
if (!_isDirected)
{
_edgesWithCost[to][from] = cost;
}
}
public IEnumerable<T> Children(T t)
{
IDictionary<T, double> tmp;
return _edgesWithCost.TryGetValue(t, out tmp) ? tmp.Keys : new List<T>();
}
private static List<T> ExtractPath(T start, T end, IDictionary<T, T> prevVertex)
{
var path = new List<T> { end };
for (; ; )
{
if (Equals(path[0], start))
{
return path;
}
if (path.Count > prevVertex.Count)
{
return null;
}
T previousIndex;
if (!prevVertex.TryGetValue(path[0], out previousIndex))
{
return null;
}
path.Insert(0, previousIndex);
}
}
public HashSet<T> Vertices { get { return new HashSet<T>(_edgesWithCost.Keys); } }
public void AddVertex(T v)
{
if (!_edgesWithCost.ContainsKey(v))
{
_edgesWithCost[v] = new Dictionary<T, double>();
}
}
public void Remove(T from, T to)
{
if (_edgesWithCost.ContainsKey(from))
{
_edgesWithCost[@from].Remove(to);
}
if (!_isDirected && _edgesWithCost.ContainsKey(to))
{
_edgesWithCost[to].Remove(@from);
}
}
public void Remove(T from)
{
_edgesWithCost.Remove(from);
foreach (var edges in _edgesWithCost)
{
edges.Value.Remove(from);
}
}
public int EdgeCount
{
get
{
var totalEdges = _edgesWithCost.Select(x => x.Value.Count).Sum();
return _isDirected ? totalEdges : totalEdges / 2;
}
}
public int VerticesCount => _edgesWithCost.Count;
public List<double> AllEdgeCost()
{
var result = new List<double>();
foreach (var targetWithCost in _edgesWithCost.Values)
{
result.AddRange(targetWithCost.Values);
}
return result;
}
private IDictionary<T, HashSet<T>> ChildrenToParents()
{
var result = new Dictionary<T, HashSet<T>>();
foreach (var start in _edgesWithCost)
foreach (var end in start.Value)
{
if (!result.ContainsKey(end.Key))
{
result.Add(end.Key, new HashSet<T>());
}
result[end.Key].Add(start.Key);
}
return result;
}
private HashSet<T> Children(IEnumerable<T> parents)
{
var result = new HashSet<T>();
foreach (var parent in parents)
{
result.UnionWith(Children(parent));
}
return result;
}
private static HashSet<T> AllParents(IEnumerable<T> children, IDictionary<T, HashSet<T>> childrenToParent)
{
var result = new HashSet<T>();
HashSet<T> tmp;
foreach (var c in children)
{
if (childrenToParent.TryGetValue(c, out tmp))
{
result.UnionWith(tmp);
}
}
return result;
}
public double CostOf(IList<T> validPath)
{
double result = 0;
for (int i = 1; i < validPath.Count; i++)
{
result += _edgesWithCost[validPath[i - 1]][validPath[i]];
}
return result;
}
/*
Shortest path:
=============
if TREE: DFS
else if Weights is a constant > 0: BFS
else if Weights are all > 0: Dijkstra
else if Weights >0 and <0 & no negative cycles: Floyd Warshall or Bellman Ford
else (graph can contains negative cycles): DFS
Longest path:
=============
if TREE: DFS
else if Weights is a constant > 0: BFS
else if no positive cycles: shortest path with Floyd Warshall or Bellman Ford (first inversing weights)
else (graph can contains positive cycles): DFS
*/
#region DFS (Depth First Search): Find shortest/longest path in o(V) (tree) to o(V!) (dense graph) time.
//Works for both negative and positive weight
public List<T> ShortestPath_DFS(T start, T end)
{
var bestPath = new List<T>();
var bestPathScore = double.MaxValue;
BestPath_DFS_Helper(new List<T> { start }, 0, end, bestPath, ref bestPathScore, true);
if (bestPath.Count == 0)
{
return null;
}
return bestPath;
}
public List<T> LongestPath_DFS(T start, T end)
{
var bestPath = new List<T>();
var bestPathScore = double.MinValue;
BestPath_DFS_Helper(new List<T> { start }, 0, end, bestPath, ref bestPathScore, false);
if (bestPath.Count == 0)
{
return null;
}
return bestPath;
}
private void BestPath_DFS_Helper(IList<T> path, double pathScore, T end, List<T> bestPath, ref double bestPathScore, bool minimizeCost)
{
var vertex = path.Last();
if (Equals(vertex, end))
{
if ((minimizeCost && pathScore < bestPathScore)
|| (!minimizeCost && pathScore > bestPathScore))
{
bestPath.Clear();
bestPath.AddRange(path);
bestPathScore = pathScore;
}
return;
}
foreach (var child in Children(vertex))
{
if (path.Contains(child))
{
continue; //already used
}
path.Add(child);
BestPath_DFS_Helper(path, pathScore + _edgesWithCost[vertex][child], end, bestPath, ref bestPathScore, minimizeCost);
path.RemoveAt(path.Count - 1);
}
}
//Find one shortest path from 'start' in o(V) (tree) to o(V!) (dense graph) time
public List<T> ShortestPath_DFS(T start)
{
if (!_edgesWithCost.ContainsKey(start))
{
return null;
}
var bestPath = new List<T>();
var bestPathScore = double.MaxValue;
BestPath_DFS_Helper(new List<T> { start }, 0, bestPath, ref bestPathScore, true);
return bestPath;
}
//Find one longest path from 'start' in o(V) (tree) to o(V!) (dense graph) time
public List<T> LongestPath_DFS(T start)
{
if (!_edgesWithCost.ContainsKey(start))
{
return null;
}
var bestPath = new List<T>();
var bestPathScore = double.MinValue;
BestPath_DFS_Helper(new List<T> { start }, 0, bestPath, ref bestPathScore, false);
return bestPath;
}
private void BestPath_DFS_Helper(List<T> path, double pathScore, List<T> bestPath, ref double bestPathScore, bool minimizeCost)
{
var vertex = path.Last();
foreach (var child in Children(vertex))
{
if (path.Contains(child))
{
continue; //already used
}
path.Add(child);
var pathScoreWithChild = pathScore + _edgesWithCost[vertex][child];
if ((minimizeCost && pathScoreWithChild < bestPathScore)
|| (!minimizeCost && pathScoreWithChild > bestPathScore))
{
bestPath.Clear();
bestPath.AddRange(path);
bestPathScore = pathScoreWithChild;
}
BestPath_DFS_Helper(path, pathScoreWithChild, bestPath, ref bestPathScore, minimizeCost);
path.RemoveAt(path.Count - 1);
}
}
//Find longest path from any two vertices in o(V) (tree) to o(V!) (dense graph) time
//works only for 'connected undidirected graph' or 'strongly connected directed graph'
public List<T> LongestPathInConnectedGraph_DFS()
{
var startVertex = LongestPath_DFS(_edgesWithCost.Keys.First()).Last();
return LongestPath_DFS(startVertex);
}
//Find longest path from any two vertices in o(V^2) (tree) to o(V*V!) (dense graph) time
//works even for not 'connected undirected graph' or not 'strongly connected directed graph'
public List<T> LongestPathInNotConnectedGraph_DFS()
{
var bestPath = new List<T>();
foreach (var v in Vertices)
{
var tmp = LongestPath_DFS(v);
if ((tmp != null) && tmp.Count > bestPath.Count)
{
bestPath = tmp;
}
}
return bestPath;
}
#endregion
#region BFS (Breadth First Search): Find one shortest path between 'start' and 'end' in o(V) time
//Works only for constant and positive weight for all edges
public List<T> ShortestPath_BFS(T start, T end)
{
var toProcess = new Queue<T>();
var prevVertex = new Dictionary<T, T>();
toProcess.Enqueue(start);
prevVertex[start] = start;
while (toProcess.Count != 0)
{
var current = toProcess.Dequeue();
if (Equals(current, end))
{
return ExtractPath(start, end, prevVertex);
}
var children = Children(current);
//children = children.OrderBy(x => x);
foreach (var c in children)
{
if (!prevVertex.ContainsKey(c))
{
prevVertex[c] = current;
toProcess.Enqueue(c);
}
}
}
return null; //no path from 'start' to 'end'
}
//Find longest path from any two vertices in o(V) time
//Works only for constant and positive weight for all edges, and for connected graph
public List<T> LongestPathInConnectedGraph_BFS()
{
var v = _edgesWithCost.Keys.First();
var longestFromV = LongestPath_BFS(v);
return LongestPath_BFS(longestFromV.Last());
}
//Find longest path from vertex 'start' in o(V) time
//Works only for constant and positive weight for all edges
public List<T> LongestPath_BFS(T start)
{
var end = AllReachable_ByDepth(start).Last().First();
return ShortestPath_BFS(start, end);
}
public List<IList<T>> All_ShortestPath_BFS(T start, T end)
{
var allPaths = new List<IList<T>>();
var allReachableForEachDepth = new List<HashSet<T>> { new HashSet<T> { start } };
var allUsedSoFar = new HashSet<T> { start };
for (; ; )
{
var lastReachable = allReachableForEachDepth[allReachableForEachDepth.Count - 1];
var newReachable = Children(lastReachable);
newReachable.ExceptWith(allUsedSoFar);
if (newReachable.Count == 0)
{
return allPaths;
}
if (newReachable.Contains(end))
{
allReachableForEachDepth.Add(new HashSet<T> { end });
break;
}
allUsedSoFar.UnionWith(newReachable);
allReachableForEachDepth.Add(newReachable);
}
var childrenToParents = ChildrenToParents();
for (int i = allReachableForEachDepth.Count - 2; i >= 1; --i)
{
allReachableForEachDepth[i].IntersectWith(AllParents(allReachableForEachDepth[i + 1], childrenToParents));
}
All_ShortestPath_BFS_Helper(allReachableForEachDepth, new List<T> { start }, allPaths);
return allPaths;
}
private void All_ShortestPath_BFS_Helper(IList<HashSet<T>> allReachableForEachDepth, IList<T> path, IList<IList<T>> allPaths)
{
if (path.Count >= allReachableForEachDepth.Count)
{
allPaths.Add(new List<T>(path));
return;
}
foreach (var c in Children(path.Last()).Intersect(allReachableForEachDepth[path.Count]))
{
path.Add(c);
All_ShortestPath_BFS_Helper(allReachableForEachDepth, path, allPaths);
path.RemoveAt(path.Count - 1);
}
}
//All vertices reachable from 'start' in o(V) time (using a BFS search)
// index '0' of the list : the 'start' vertex itself
// index '1' of the list : new vertices reachable in 1 move (minimum)
// index '2' of the list : new vertices reachable in 2 move (minimum)
// etc...
// look only for vertices reachable in less the 'maxDepth' moves
public List<HashSet<T>> AllReachable_ByDepth(T start, int maxDepth = int.MaxValue)
{
var visited = new Dictionary<T, int>();
visited[start] = 0;
var toProcess = new Queue<T>();
toProcess.Enqueue(start);
int observedMaxDepth = 0;
while (toProcess.Count != 0)
{
var current = toProcess.Dequeue();
foreach (var child in Children(current))
{
if (visited.ContainsKey(child))
{
continue;
}
int newDepth = visited[current] + 1;
if (newDepth > maxDepth)
{
continue;
}
visited[child] = newDepth;
observedMaxDepth = Math.Max(observedMaxDepth, newDepth);
toProcess.Enqueue(child);
}
}
var result = new List<HashSet<T>>();
while (result.Count <= observedMaxDepth)
{
result.Add(new HashSet<T>());
}
foreach (var e in visited)
{
result[e.Value].Add(e.Key);
}
return result;
}
//All vertices reachable from 'start' in o(V) time (using a BFS search)
//returns only vertices that are reachable in less then 'maxDepth' moves
//always includes the starting vertice 'start'
public List<T> AllReachable(T start, int maxDepth = int.MaxValue) {return new List<T>(AllReachable_ByDepth(start, maxDepth).SelectMany(x => x));}
#endregion
#region Dijkstra: Find one shortest path in o (E + V Log(V) ) time
//Works only for weights >= 0
public List<T> ShortestPath_Dijkstra(T start, T end)
{
var unvisitedVertices = new HashSet<T>();
var minDistance = new PriorityQueue<T>(true);
var infiniteCost = double.MaxValue;
var minCostToReachVertex = new Dictionary<T, double>();
var prevVertex = new Dictionary<T, T>();
foreach (var v in _edgesWithCost.Keys)
{
minCostToReachVertex[v] = infiniteCost;
minDistance.Enqueue(v, Equals(v, start) ? 0 : infiniteCost);
unvisitedVertices.Add(v);
}
minCostToReachVertex[start] = 0;
while (minDistance.Count != 0)
{
var nearestNeighbor = minDistance.Dequeue();
unvisitedVertices.Remove(nearestNeighbor);
var bestCostToNearestNeighbor = minCostToReachVertex[nearestNeighbor];
if (bestCostToNearestNeighbor == infiniteCost)
{
return null;
}
if (Equals(nearestNeighbor, end))
{
break;
}
foreach (var childOfNearestNeighbor in unvisitedVertices.Intersect(Children(nearestNeighbor)))
{
var newCostIfUsingNearestNeighbor = bestCostToNearestNeighbor + _edgesWithCost[nearestNeighbor][childOfNearestNeighbor];
var previousCostWithoutNearestNeighbor = minCostToReachVertex[childOfNearestNeighbor];
if ((previousCostWithoutNearestNeighbor == infiniteCost) //there was no known path from 'start' to 'end' before using 'nearestNeighbor'
|| (newCostIfUsingNearestNeighbor < previousCostWithoutNearestNeighbor) //less expensive path
)
{
minDistance.UpdatePriority(childOfNearestNeighbor, previousCostWithoutNearestNeighbor, newCostIfUsingNearestNeighbor);
minCostToReachVertex[childOfNearestNeighbor] = newCostIfUsingNearestNeighbor;
prevVertex[childOfNearestNeighbor] = nearestNeighbor;
}
}
}
return ExtractPath(start, end, prevVertex);
}
#endregion
#region Bellman-Ford Algorhitm: find all shortest path starting from 'start' in o (V E) time
//Works for negative weight
//Doesn't work if negative cycles (returns null if graph contains negative cycles)
public List<T> BestPathBellmanFord(T start, T end, bool minimizeCost, List<T> negativeCycleIfAny = null, Func<T, T, double> costOverrideIfAny = null)
{
var infiniteCost = minimizeCost ? double.MaxValue : double.MinValue;
var prevVertex = new Dictionary<T, T>();
var bestDistanceFromStart = new Dictionary<T, double>();
var allVertices = Vertices;
foreach (var v in allVertices)
{
bestDistanceFromStart[v] = infiniteCost;
}
bestDistanceFromStart[start] = 0;
//a shortest path (without cycle) between any vertices 'u' & 'v' takes at most 'V' nodes and 'V-1' edges
//we'll make 'V-1' steps and, at each step:
// for each existing edge (u,v)
// we'll use this edge (u,v) to improve the best path between 'start' & 'v'
for (int i = 0; i < allVertices.Count; ++i) // 'V-1' steps
{
foreach (var e in _edgesWithCost)
{
var u = e.Key;
foreach (var targetWithCost in e.Value)
{
var v = targetWithCost.Key;
if (bestDistanceFromStart[u] == infiniteCost)
{
continue;
}
var costUV = (costOverrideIfAny == null)?targetWithCost.Value: costOverrideIfAny(u, v);
var newCost = bestDistanceFromStart[u] + costUV;
if ((bestDistanceFromStart[v] == infiniteCost)
|| (minimizeCost && (newCost < bestDistanceFromStart[v]))
|| (!minimizeCost && (newCost > bestDistanceFromStart[v]))
)
{
bestDistanceFromStart[v] = newCost;
prevVertex[v] = u;
}
}
}
}
//Negative-weight cycle detection:
//With the 'V-1' steps above:
// we have computed (in 'bestDistanceFromStart') all best path from 'start' using at most 'V-1' edges
//We'll make one more step:
// if this step can improve any best path, it means that the new best path is using a negative cycle
foreach (var e in _edgesWithCost)
{
var u = e.Key;
foreach (var targetWithCost in e.Value)
{
var v = targetWithCost.Key;
if ((bestDistanceFromStart[u] == infiniteCost) || (bestDistanceFromStart[v] == infiniteCost))
{
continue;
}
var costUV = (costOverrideIfAny == null) ? targetWithCost.Value : costOverrideIfAny(u, v);
var newCost = bestDistanceFromStart[u] + costUV;
//if distance between 'u' & 'v' can be improved
if ((minimizeCost && (newCost < bestDistanceFromStart[v]))
//||(!minimizeCost && (newCost > vertexToCost[v]))
)
{
//Graph contains a negative-weight cycle
if (negativeCycleIfAny != null)
{
negativeCycleIfAny.Clear();
negativeCycleIfAny.AddRange(ExtractCyclePath(v, prevVertex) ?? new List<T>());
}
return null;
}
}
}
return ExtractPath(start, end, prevVertex);
}
private static List<T> ExtractCyclePath(T end, IDictionary<T, T> prevVertex)
{
var cycle = new List<T> { end };
for (; ; )
{
if (cycle.Count > prevVertex.Count + 1)
{
return null;
}
T previousIndex;
if (!prevVertex.TryGetValue(cycle.Last(), out previousIndex))
{
return null;
}
var idx = cycle.IndexOf(previousIndex);
if (idx >= 0)
{
cycle = cycle.GetRange(idx, cycle.Count - idx);
cycle.Reverse();
return cycle;
}
cycle.Add(previousIndex);
}
}
/// <summary>
/// return a negative cycle in the graph (if any) in o(V E) time
/// </summary>
/// <param name="notUsedRoot"></param>
/// <param name="costOverrideIfAny"></param>
/// <returns>
/// a negative cycle, or null if no negative cycle exist in teh graph</returns>
public List<T> ExtractNegativeCycleIfAny(T notUsedRoot, Func<T, T, double> costOverrideIfAny = null)
{
if (_isDirected)
{
foreach (var v in Vertices)
{
Add(notUsedRoot, v, 0);
}
}
var cycleWithNegativeWeight = new List<T>();
var tmp = BestPathBellmanFord(notUsedRoot, Vertices.First(), true, cycleWithNegativeWeight, costOverrideIfAny);
Remove(notUsedRoot);
if (tmp != null)
{
return null; //no negative cycle;
}
return cycleWithNegativeWeight;
}
//find the shortest path between 'start' and 'end' using at most 'maxDepth' edges in o(maxDepth * E) time
public double BestPathBellmanFordWithMaxDepth(T start, T end, int maxDepth)
{
//bestDistanceFromStart[v][d] : shortest path from 'start' to 'v' using at most 'd' edges
var bestDistanceFromStart = new Dictionary<T, double[]>();
foreach (var v in Vertices)
{
bestDistanceFromStart[v] = Enumerable.Repeat(Equals(v, start) ? 0 : double.MaxValue, 1 + maxDepth).ToArray();
}
for (int depth = 1; depth <= maxDepth; ++depth)
{
foreach (var e in _edgesWithCost)
{
var edgeStart = e.Key;
var shortestPathToEdgeStartAtPreviousDepth = bestDistanceFromStart[edgeStart][depth - 1];
if (shortestPathToEdgeStartAtPreviousDepth == double.MaxValue)
{
continue;
}
foreach (var edgeEndWithCost in e.Value)
{
var edgeEnd = edgeEndWithCost.Key;
var edgeCost = edgeEndWithCost.Value;
//we check if we can improve the path 'start' => 'edgeEnd' using the current edge 'e'
bestDistanceFromStart[edgeEnd][depth] = Math.Min(bestDistanceFromStart[edgeEnd][depth], shortestPathToEdgeStartAtPreviousDepth + edgeCost);
}
}
}
return (bestDistanceFromStart[end][maxDepth] == double.MaxValue) ? -1 : bestDistanceFromStart[end][maxDepth];
}
#endregion
#region Tramp Steamer Problem : find the cycle with the optimal ratio (cycle edge sum) / (cycle duration)
/// <summary>
/// Solve the Tramp Steamer Problem
/// each edge 'A' => 'B' has a given cost, and an associate duration (= duration(A,B) )
/// the goal is to find a cycle minimizing the ratio (cycle cost)/(cycle duration)
/// Complexity: o( log(sum(duration)) V E )
/// </summary>
/// <returns>
/// null if there is no cycle in the graph
/// Tuple.Item1 : the lowest ratio 'cycle cost/cycle duration' we can achieve in a cycle
/// Tuple.Item2 : the cycle achieving this lowest ratio
/// </returns>
///
public Tuple<double, List<T>> CycleWithLowestRatioCostDuration(T notUsedRoot, Func<T, T, double> duration)
{
double min = 0.00001;
double max = 1e9;
if (null != ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => _edgesWithCost[u][v] - min * duration(u, v)))
{
return null;
}
var lastNotNullCycle = ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => _edgesWithCost[u][v] - max * duration(u, v));
if (lastNotNullCycle == null)
{
return null;
}
while (min < max)
{
if (Math.Abs(max - min) < 1e-6)
{
break;
}
var middle = (min + max) / 2;
var negCycle = ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => _edgesWithCost[u][v] - middle * duration(u, v));
if (negCycle == null)
{
min = middle;
}
else
{
lastNotNullCycle = negCycle;
max = middle;
}
}
return Tuple.Create((max + min) / 2, lastNotNullCycle);
}
/// <summary>
/// Solve the Tramp Steamer Problem
/// each edge 'A' => 'B' has a given profit, and an associate duration (= duration(A,B) )
/// the goal is to find a cycle maximizing the ratio (cycle profit)/(cycle duration)
/// Complexity: o( log(sum(duration)) V E )
/// </summary>
/// <returns>
/// null if there is no cycle in the graph
/// Tuple.Item1 : the highest ratio 'profit/duration' we can achieve in a cycle
/// Tuple.Item2 : the cycle achieving this highest ratio
/// </returns>
public Tuple<double, List<T>> CycleWithHighestRatioBenefitDuration(T notUsedRoot, Func<T, T, double> duration)
{
double min = 0.00001;
double max = 1e9;
if (null != ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => -_edgesWithCost[u][v] + max * duration(u, v)))
{
return null;
}
var lastNotNullCycle = ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => -_edgesWithCost[u][v] + min * duration(u, v));
if (lastNotNullCycle == null)
{
return null;
}
while (min < max)
{
if (Math.Abs(max - min) < 1e-6)
{
break;
}
var middle = (min + max) / 2;
var negCycle = ExtractNegativeCycleIfAny(notUsedRoot, (u, v) => -_edgesWithCost[u][v] + middle * duration(u, v));
if (negCycle == null)
{
max = middle;
}
else
{
lastNotNullCycle = negCycle;
min = middle;
}
}
return Tuple.Create((max + min) / 2, lastNotNullCycle);
}
#endregion
#region Floyd Warshall Algorithm: find all shortest path between any vertex in o (V^3) time
//Works for negative weight
//Doesn't work if negative cycles (returns null if graph contains negative cycles)
public Tuple<double, List<T>> BestPathFloydWarshall(T start, T end, bool minimizeCost)
{
IDictionary<T, IDictionary<T, T>> pathToNext;
IDictionary<T, IDictionary<T, double>> costResult = FloydWarshallAlgorithm(minimizeCost, out pathToNext);
if (costResult == null || (!pathToNext.ContainsKey(start)) || (!pathToNext[start].ContainsKey(end)))
{
return null;
}
var bestPath = ExtractBestPathFloydWarshallAlgorithm(start, end, pathToNext);
if (bestPath == null)
{
return null;
}
var bestCost = CostOf(bestPath);
return Tuple.Create(bestCost, bestPath);
}
// minimizeCost:
// true if we are looking for the less expensive path from any of vertices
// false if we are looking for the most expensive path from any pair of vertices
// return value:
// a result matrix where costResult[start][end] is the optimal cost from 'start' to 'end', or infiniteCost if there are no such paths
private IDictionary<T, IDictionary<T, double>> FloydWarshallAlgorithm(bool minimizeCost, out IDictionary<T, IDictionary<T, T>> pathToNext)
{
var infiniteCost = minimizeCost ? double.MaxValue : double.MinValue;
var costResult = new Dictionary<T, IDictionary<T, double>>();
pathToNext = new Dictionary<T, IDictionary<T, T>>();
var allVertices = Vertices.ToList();
foreach (var u in allVertices)
{
costResult[u] = new Dictionary<T, double>();
pathToNext[u] = new Dictionary<T, T>();
foreach (var v in allVertices)
{
costResult[u][v] = infiniteCost;
}
costResult[u][u] = 0;
}
foreach (var e in _edgesWithCost) //We add all existing edge
{
var u = e.Key;
foreach (var toWithCost in e.Value)
{
var v = toWithCost.Key;
costResult[u][v] = toWithCost.Value;
pathToNext[u][v] = v;
}
}
foreach (var i in allVertices) // intermediate vertex
{
foreach (var u in allVertices)
{
foreach (var v in allVertices)
{
//costResult[u][v] is the minimal cost from 'u' to 'v' using only vertices between 0 and 'i-1';
//we check if using vertex 'i' can improve the result
double uiCost = costResult[u][i];
if (uiCost == infiniteCost) // no path from 'u' to 'i' at this point
{
continue;
}
double ivCost = costResult[i][v];
if (ivCost == infiniteCost) // no path from 'i' to 'v' at this point
{
continue;
}
var uivCost = uiCost + ivCost;
var uvCost = costResult[u][v];
if ((uvCost == infiniteCost) //there was no known path from 'u' to 'v' before using vertex 'i'
|| (minimizeCost && (uivCost < uvCost)) //less expensive path
|| ((!minimizeCost) && (uivCost > uvCost)) //most expensive path
)
{
costResult[u][v] = uivCost;
pathToNext[u][v] = pathToNext[u][i];
}
}
if (costResult[u][u] < 0) //negative cycle detected
{
pathToNext = null;
return null;
}
}
}
return costResult;
}
private List<T> ExtractBestPathFloydWarshallAlgorithm(T start, T end, IDictionary<T, IDictionary<T, T>> pathToNext)
{
var path = new List<T> { start };
if (Equals(start, end))
{
return path;
}
if (pathToNext == null || !pathToNext.ContainsKey(start) || !pathToNext[start].ContainsKey(end))
{
return null;
}
while (!Equals(start, end))
{
start = pathToNext[start][end];
path.Add(start);
}
return path;
}
#endregion
#region 2-SAT
/// <summary>
/// Solve 2SAT Problem in o(E+V) Time with clauses as input
/// </summary>
/// <param name="clauses">
/// List of clauses: all of them must be satisfied at the same time
/// Each element of the list (a Tuple) if a disjunction:
/// at least one of the 2 constraints (Tuple.Item1 or Tuple.Item2) must be satisfied
/// </param>
/// <param name="Complement">compute the complement of a constraint a => ~a , ~a => a</param>
/// <param name="AreValidAtSameTime">true if the 2 constraints can be valid at same time
/// Those constraints will always come from the original clauses list
/// Only needed if 'distinctConstraintsAreAlwaysValidAtSameTime' is false
/// </param>
/// <param name="distinctConstraintsAreAlwaysValidAtSameTime">
/// true if 2 distinct constraints are always valid at same time
/// so only 'a' and '~a' are not valid at same time, all other combinations of constraints are valid
/// </param>
/// <returns>
/// For each clause, the constraint (Tuple.Item1 or Tuple.Item2) to satisfy the 2SAT problem
/// null if it is not possible to satisfy all clauses at the same time
/// </returns>
public static List<T> Solve2SAT(List<Tuple<T, T>> clauses, Func<T, T> Complement, Func<T, T, bool> AreValidAtSameTime, bool distinctConstraintsAreAlwaysValidAtSameTime)
{
//We construct the implication graph
var implicationGraph = new Graph<T>(true);
foreach (var disjunction in clauses)
{
//a disjunction (a or b) is equivalent to ( (~a => b) and (~b => a) )
implicationGraph.Add(Complement(disjunction.Item1), disjunction.Item2, 1);
implicationGraph.Add(Complement(disjunction.Item2), disjunction.Item1, 1);
}
if (!distinctConstraintsAreAlwaysValidAtSameTime)
{
for (int first = 0; first < clauses.Count; ++first)
{
var constraint1 = clauses[first].Item1;
var constraint2 = clauses[first].Item2;
for (int other = first + 1; other < clauses.Count; ++other)
{
var otherConstraint1 = clauses[other].Item1;
var otherConstraint2 = clauses[other].Item2;
if (!AreValidAtSameTime(clauses[first].Item1, (clauses[other].Item1)))
{
implicationGraph.Add(constraint1, Complement(otherConstraint1), 1);
implicationGraph.Add(otherConstraint1, Complement(constraint1), 1);
}
if (!AreValidAtSameTime(clauses[first].Item1, (clauses[other].Item2)))
{
implicationGraph.Add(constraint1, Complement(otherConstraint2), 1);
implicationGraph.Add(otherConstraint2, Complement(constraint1), 1);
}
if (!AreValidAtSameTime(clauses[first].Item2, (clauses[other].Item1)))
{
implicationGraph.Add(constraint2, Complement(otherConstraint1), 1);
implicationGraph.Add(otherConstraint1, Complement(constraint2), 1);
}
if (!AreValidAtSameTime(clauses[first].Item2, (clauses[other].Item2)))
{
implicationGraph.Add(constraint2, Complement(otherConstraint2), 1);
implicationGraph.Add(otherConstraint2, Complement(constraint2), 1);
}
}
}
}
var sccInTopologicalOrder = implicationGraph.ExtractStronglyConnectedComponents();
var constraintsThatMustBeSatisfied = new HashSet<T>();
var constraintToSccId = new Dictionary<T, int>(); //'constraint' to associated 'strongly connected component id'
for (var sccId = 0; sccId < sccInTopologicalOrder.Count; sccId++)
{
var component = sccInTopologicalOrder[sccId];
foreach (var constraintId in component)
{
var constraintIdComplement = Complement(constraintId);
if (constraintToSccId.TryGetValue(constraintIdComplement, out var sccIdOfConstraintComplement))
{
if (sccIdOfConstraintComplement == sccId)
{
return null; //both the constraint and its complement are in the same SCC : no solution
}
constraintsThatMustBeSatisfied.Add(sccIdOfConstraintComplement <= sccId ? constraintId : constraintIdComplement);
}
constraintToSccId[constraintId] = sccId;
}
}
var solutions = new List<T>();
foreach (var clause in clauses)
{
if (constraintsThatMustBeSatisfied.Contains(clause.Item1) || constraintsThatMustBeSatisfied.Contains(Complement(clause.Item2)))
{
solutions.Add(clause.Item1);
}
else
{
solutions.Add(clause.Item2);
}
}
return solutions;
}
#endregion
#region Strongly connected components
/// <summary>
/// Strongly connected component Detection in o(|V| + |E|) ( => o(n) for tree , o(n^2) for fully connected graph)
/// Strongly connected component: Largest sub graph where for any 2 vertices 'u' & 'v' of this sub graph, there is a path from 'u' to 'v' and a path from 'v' to 'u'
/// </summary>
/// <returns>
/// List of Strongly connected component in Topological order
/// </returns>
public List<List<T>> ExtractStronglyConnectedComponents()
{
var stronglyConnectedComponents = new List<List<T>>();
var dfsIndex = new Dictionary<T, int>();
var lowLinkDfsIndex = new Dictionary<T, int>();
var allVertices = Vertices;
foreach (var v in allVertices)
{
dfsIndex[v] = lowLinkDfsIndex[v] = -1;
}
var nextDfsIndex = 0;
var verticesInStack = new Stack<T>();
foreach (var v in allVertices)
{
if (dfsIndex[v] == -1)
{
StronglyConnectedComponent(v, stronglyConnectedComponents, dfsIndex, lowLinkDfsIndex, verticesInStack, ref nextDfsIndex);
}
}
//the SCC are currently in inverse Topological order: we need to invert the order to make them in topological order
stronglyConnectedComponents.Reverse();
return stronglyConnectedComponents;
}
private void StronglyConnectedComponent(T v, List<List<T>> stronglyConnectedComponents, IDictionary<T, int> dfsIndex, IDictionary<T, int> sccId, Stack<T> stack, ref int nextDfsIndex)
{
Debug.Assert(dfsIndex[v] == -1);
dfsIndex[v] = nextDfsIndex;
//the sccId associated with 'v' will remain at 'nextDfsIndex' if 'v' is the root of a scc (or if it is a single point scc)
//it will change to a lower sccId if 'v' belongs to a scc associated with a vertex already meet previously during the dfs
sccId[v] = nextDfsIndex;
++nextDfsIndex;
stack.Push(v);
foreach (var w in Children(v))
{
if (dfsIndex[w] == -1)
{
//Child 'w' has not yet been visited; recurse on it
StronglyConnectedComponent(w, stronglyConnectedComponents, dfsIndex, sccId, stack, ref nextDfsIndex);
sccId[v] = Math.Min(sccId[v], sccId[w]);
continue;
}
if (stack.Contains(w)) //Child 'w' is in stack and hence in the current SCC
{
sccId[v] = Math.Min(sccId[v], dfsIndex[w]);
}
}
// If 'v' is a root vertex, pop the stack and generate a new SCC
if (dfsIndex[v] == sccId[v])
{
var newStronglyConnectedComponent = new List<T>();
for (; ; )
{