×

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search, Dijkstra's technique, and the bidirectional approach. Dijkstra's algorithm is the one that's most frequently employed. One limitation of the approach is that it cannot be used for graphs with negative edge weights. Another distinction is that although Bellman-Ford iterates through each edge, the Dijkstra method only considers a vertex's immediate neighbors.

The solution to this problem may be found using the Bellman-Ford algorithm. The two low-edge weights are the subject of everything. This section will explain the Bellman-Ford algorithm using examples and demonstrate how to use it in a Java program.

The Bellman-Ford Algorithm

It is similar to Dijkstra's algorithm and uses a single-source shortest path (lowest weight) approach. When we need to determine the shortest route in a graph, we may utilize it. It solves the with negative edge weights, as you might have seen. A cycle's ability to create a negative result when its edges are added together is a limitation of the algorithm. Take into consideration the cycled graph below.

Bellman Ford Algorithm Java

The algorithm's storage and time complexity are both (v*e) (v). The procedure should be used if the graph's edge weights are negative. The Bellman-Ford algorithm is thus applicable in the following circumstances:

  • Negatively weighted edges
  • Indirect Cycles with Positive Edge Weights > 1

In the case of all negative arcs, the technique is very slower than Dijkstra's algorithm.

Steps for finding the Shortest path

The Bellman-Ford algorithm's steps for determining the shortest path from the source to each vertex are as follows:

  • In this stage, the source's distance to every vertex is set to infinity, while the source's distance is set to 0. Make an array dist[] of size |V| except dist[src], the source vertex having all values set to infinity.
  • The smallest distances are computed in this stage. Execute the steps below |V|-1 times, where |V| seems to be the number of a vertex in the graphs g. For every edge u-v, repeat these procedures. Follow these steps for each edge u-v. Increase dist[v] to dist[v] = dist[u] + weight of edge UV if dist[v] > dist[u] + weight of the edge UV.
  • When there is a negative weight cycle inside the graph, the next step reports it. Once more, travel along each edge and perform steps u-v for each edge. Graph demonstrates negative weighted cycle if dist[v] > dist[u] + edge weight uvUV.
  • The idea underlying step 3 is that if the graph doesn't have a negative weight of the cycle, step 2 assures the very lowest lengths. There is a negative value cycle if we iterate throughout all edges one further time and obtain the shortest route for every vertex.

How The Bellman-Ford Algorithm Works

The Bellman-Ford algorithm functions similarly to Dijkstra's algorithm. Like Dijkstra's algorithm, it repeatedly cycles over all edges and changes the lengths at the initial node. The key difference is that the prioritized queue does not get used. Sometimes shortest paths might not exist if a graph G=(V, E) has a negative weight cycle. The Bellman-Ford algorithm identifies a negative weight cycle or all shortest paths from the source of length s to all destinations of length v.

The technique gives a boolean value of TRUE when and only if the weighted directed graph G(V, E) does not contain any negative-weight cycles that can reach first from the source. The algorithm generates the weights as well as the shortest path. The method suggests there is no answer when such a cycle exists. There is an answer when such a cycle exists.

Algorithm

INITIALIZE-SOURCE (G, s)  
for i <- 1 to |V[G]|-1  
do for each edge (U, V) ϵ E[G]  
do RELAX (U, V, W)  
for each edge (U, V) ϵ E[G]  
do if distance[V] > distance[U] + w(U, V)  
then return FALSE  
return TRUE  

Pseudo code for Bellman Ford Algorithm

BellamanFord (G, V, E, S)  
Step1:  
for each vertex v ϵ G do  
distance[v] = ∞  
distance[source] =  0
  
Step 2:  
Relax (u, v, w)  
for i = 1 to |v|-1  
           for each edge (u, v) ϵ G do  
           (distance[v] > distance[u]+w(u, v))  
           (distance[v] <- distance[u]+w(u, v))  
Step 3:  
for each edge (u, v) ϵ G  
if (distance[u]+w(u, v)< distance[v])  
return "Graph G contains the negative cycle.”  
return distance  

Java Program for the implementation of the Bellman Ford algorithm

BellmanFord.java

import java.util.ArrayList;  
import java.util.List;  
//class Graphs are created
class Graphs   
{  
//the vertices of the graph G  
private int Vertex;    
//edges in the graph  
private List<Edge> edges;   
//constructing a Graph class function Object() { [native code] } and producing getters and setters
public Graphs(int v)   
{  
Vertex= v;  
edges= new ArrayList<Edge>();  
}  
public int getV()   
{  
return Vertex;  
}  
public void setV(int v)   
{  
Vertex= v;  
}  
public List<Edge> getEdges()   
{  
return edges;  
}  
public void setEdges(List<Edge> edges)   
{  
this.edges = edges;  
}  
public void addEdge(int u, int v, int w)   
{  
Edge e1 = new Edge(u, v, w);  
edges.add(e1);  
}  
}  
class Edge   
{  
//the vertex u is the initial
private int u;   
//the vertex v is the destination vertex
private int v;   
//w denotes the weight of the edge  
private int w;   
//getting and setting getters  
public int getU()   
{  
return u;  
}  
public void setU(int u)   
{  
this.u = u;  
}  
public int getV()   
{  
return v;  
}  
public void setV(int v)   
{  
this.v = v;  
}  
public int getW()   
{  
return w;  
}  
public void setW(int w)   
{  
this.w = w;  
}  
//A constructor was created for the class Edge with the parameters
public Edge(int u, int v, int w)   
{  
this.u = u;  
this.v = v;  
this.w = w;  
}  
}  
//main section of the program
public class BellmanFord 
{  
public static void main(String args[])   
{  
Graphs g1 = createGraphs();  
int distance[] = new int[g1.getV()];  
boolean NegativeCycle = getShortestdistance(g1, 1, distance);  
if(!NegativeCycle)   
{  
System.out.println("VERTEX \t:DISTANCE");      
for(int i = 1; i < distance.length; i++)  
System.out.println("\t"+i + " " + "\t\t"+(distance[i] == Integer.MAX_VALUE ? "-" : distance[i]));  
}   
else   
{  
System.out.println("THE GRAP DOES NOT CONTAIN THE NEGATIVE CYCLES");  
}  
}  
private static Graphs createGraphs()   
{  
int v = 7;  
//A graph g2 having the 7 seven vertices is created  
Graphs g2 = new Graphs(v);  
// the edges are added to the graph g2 
g2.addEdge(1, 2, 4);  
g2.addEdge(1, 4, 9);  
g2.addEdge(2, 3, -1);  
g2.addEdge(3, 6, 3);  
g2.addEdge(4, 3, 2);  
g2.addEdge(4, 5, -5);  
g2.addEdge(5, 6, 0);       
//the function will return th egraph
return g2;  
}  
// logic for bellman ford algorithm 
public static boolean getShortestdistance(Graphs g, int source, int[] distance)   
{  
int Vertex = g.getV();  
// the distance from the source to the other vertices is given 
for(int i = 1; i < Vertex; i++)   
{  
distance[i] = Integer.MAX_VALUE;  
}  
// the source vertex has the initial value as 0
distance[source] = 0;  
// the edges are then relaxed  
for(int i = 1; i < Vertex; i++)   
{  
// by the for loop, the vertices of the graph are iterated     
for(Edge e: g.getEdges())   
{  
int u = e.getU(), v = e.getV(), w = e.getW();  
if(distance[u] != Integer.MAX_VALUE && distance[v] > distance[u] + w)   
{  
// the value of the total distance is calculated     
distance[v] = distance[u] + w;  
}  
}  
}  
//the condition will check whether it contains any negative cycles 
for(Edge e: g.getEdges())   
{  
int u = e.getU(), v = e.getV(), w = e.getW();  
if(distance[u] != Integer.MAX_VALUE && distance[v] > distance[u] + w)   
{  
return true;  
}  
}  
return false;  
} 
} 

Output:

Bellman Ford Algorithm Java

Note:

Numerous graphing programs use negative weights. For instance, if we follow a particular path, we might gain something instead of paying for it.

Fort, he distributed systems, Bellman-Ford performs better (better than Dijkstra's).   Contrary to Dijkstra's, which must determine each vertex's minimum value, Bellman-Ford takes each edge into account individually.

Bellman-Ford cannot solve an undirected network having negative edges because it will be classified as a negative cycle.

Summary

Finding the shortest route through a graph with positive edge weights is an NP-hard problem. There isn't any polynomial-time algorithm for resolving such issues. We can use the Bellman-Ford method in a case where each edge has a negative edge weight.

Cannot use the Bellman-Ford approach to determine the longest simple path between a source (s) and the vertex (v) if the graphs have negative cycles. It's possible to go to a negative-weight cycle from either source. Will stop the algorithm in this situation.


Related Topics

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.