-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNegativeCycleDetectionBellmanFordBased.cs
More file actions
49 lines (39 loc) · 1.52 KB
/
NegativeCycleDetectionBellmanFordBased.cs
File metadata and controls
49 lines (39 loc) · 1.52 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
using AlgorithmsAndDataStructures.Algorithms.Graph.Common;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
public class NegativeCycleDetectionBellmanFordBased
{
#pragma warning disable CA1822 // Mark members as static
public bool HasNegativeCycle(WeightedGraphVertex[] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return default;
var distance = new int[graph.Length];
var distanceChanged = true;
for (var i = 1; i < graph.Length; i++) distance[i] = int.MaxValue;
// Algorithm performs only V -1 cycles here to avoid being caught in negative cycle.
for (var j = 0; j < graph.Length - 1 && distanceChanged; j++)
for (var i = 0; i < graph.Length - 1 && distanceChanged; i++)
{
var vertex = graph[i];
distanceChanged = false;
foreach (var edge in vertex.Edges)
if (distance[edge.To] > distance[i] + edge.Weight)
{
distance[edge.To] = distance[i] + edge.Weight;
distanceChanged = true;
}
}
for (var i = 0; i < graph.Length; i++)
{
var vertex = graph[i];
distanceChanged = false;
foreach (var edge in vertex.Edges)
if (distance[edge.To] > distance[i] + edge.Weight)
{
distanceChanged = true;
break;
}
}
return distanceChanged;
}
}