Skip to content

Commit 7e2ee49

Browse files
committed
feat: implement Bellman Ford algorithm
1 parent c91a7ca commit 7e2ee49

1 file changed

Lines changed: 107 additions & 0 deletions

File tree

Programs/BellmanFord.java

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Bellman Ford Algorithm in Java
2+
3+
class CreateGraph {
4+
5+
// CreateGraph - it consists of edges
6+
class CreateEdge {
7+
int s, d, w;
8+
9+
CreateEdge() {
10+
s = d = w = 0;
11+
}
12+
};
13+
14+
int V, E;
15+
CreateEdge edge[];
16+
17+
// Creates a graph with V vertices and E edges
18+
CreateGraph(int v, int e) {
19+
V = v;
20+
E = e;
21+
edge = new CreateEdge[e];
22+
for (int i = 0; i < e; ++i)
23+
edge[i] = new CreateEdge();
24+
}
25+
26+
void BellmanFord(CreateGraph graph, int s) {
27+
int V = graph.V, E = graph.E;
28+
int dist[] = new int[V];
29+
30+
// Step 1: fill the distance array and predecessor array
31+
for (int i = 0; i < V; ++i)
32+
dist[i] = Integer.MAX_VALUE;
33+
34+
// Mark the source vertex
35+
dist[s] = 0;
36+
37+
// Step 2: relax edges |V| - 1 times
38+
for (int i = 1; i < V; ++i) {
39+
for (int j = 0; j < E; ++j) {
40+
// Get the edge data
41+
int u = graph.edge[j].s;
42+
int v = graph.edge[j].d;
43+
int w = graph.edge[j].w;
44+
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v])
45+
dist[v] = dist[u] + w;
46+
}
47+
}
48+
49+
// Step 3: detect negative cycle
50+
// if value changes then we have a negative cycle in the graph
51+
// and we cannot find the shortest distances
52+
for (int j = 0; j < E; ++j) {
53+
int u = graph.edge[j].s;
54+
int v = graph.edge[j].d;
55+
int w = graph.edge[j].w;
56+
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
57+
System.out.println("CreateGraph contains negative w cycle");
58+
return;
59+
}
60+
}
61+
62+
// No negative w cycle found!
63+
// Print the distance and predecessor array
64+
printSolution(dist, V);
65+
}
66+
67+
// Print the solution
68+
void printSolution(int dist[], int V) {
69+
System.out.println("Vertex Distance from Source");
70+
for (int i = 0; i < V; ++i)
71+
System.out.println(i + "\t\t" + dist[i]);
72+
}
73+
74+
public static void main(String[] args) {
75+
int V = 5; // Total vertices
76+
int E = 8; // Total Edges
77+
78+
CreateGraph graph = new CreateGraph(V, E);
79+
80+
// edge 0 --> 1
81+
graph.edge[0].s = 0;
82+
graph.edge[0].d = 1;
83+
graph.edge[0].w = 5;
84+
85+
// edge 0 --> 2
86+
graph.edge[1].s = 0;
87+
graph.edge[1].d = 2;
88+
graph.edge[1].w = 4;
89+
90+
// edge 1 --> 3
91+
graph.edge[2].s = 1;
92+
graph.edge[2].d = 3;
93+
graph.edge[2].w = 3;
94+
95+
// edge 2 --> 1
96+
graph.edge[3].s = 2;
97+
graph.edge[3].d = 1;
98+
graph.edge[3].w = 6;
99+
100+
// edge 3 --> 2
101+
graph.edge[4].s = 3;
102+
graph.edge[4].d = 2;
103+
graph.edge[4].w = 2;
104+
105+
graph.BellmanFord(graph, 0); // 0 is the source vertex
106+
}
107+
}

0 commit comments

Comments
 (0)