-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellmanFords.cs
68 lines (55 loc) · 1.56 KB
/
BellmanFords.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
public struct Edge
{
public int Source;
public int Destination;
public int Weight;
}
public struct Graph
{
public int VerticesCount;
public int EdgesCount;
public Edge[] edge;
}
public static Graph CreateGraph(int verticesCount, int edgesCount)
{
Graph graph = new Graph();
graph.VerticesCount = verticesCount;
graph.EdgesCount = edgesCount;
graph.edge = new Edge[graph.EdgesCount];
return graph;
}
private static void Print(int[] distance, int count)
{
Console.WriteLine("Vertex Distance from source");
for (int i = 0; i < count; ++i)
Console.WriteLine("{0}\t {1}", i, distance[i]);
}
public static void BellmanFord(Graph graph, int source)
{
int verticesCount = graph.VerticesCount;
int edgesCount = graph.EdgesCount;
int[] distance = new int[verticesCount];
for (int i = 0; i < verticesCount; i++)
distance[i] = int.MaxValue;
distance[source] = 0;
for (int i = 1; i <= verticesCount - 1; ++i)
{
for (int j = 0; j < edgesCount; ++j)
{
int u = graph.edge[j].Source;
int v = graph.edge[j].Destination;
int weight = graph.edge[j].Weight;
if (distance[u] != int.MaxValue && distance[u] + weight < distance[v])
distance[v] = distance[u] + weight;
}
}
for (int i = 0; i < edgesCount; ++i)
{
int u = graph.edge[i].Source;
int v = graph.edge[i].Destination;
int weight = graph.edge[i].Weight;
if (distance[u] != int.MaxValue && distance[u] + weight < distance[v])
Console.WriteLine("Graph contains negative weight cycle.");
}
Print(distance, verticesCount);
}