0% found this document useful (0 votes)
40 views2 pages

Java Implementation of Bellman-Ford Algorithm

The document contains a Java implementation of the Bellman-Ford algorithm for finding the shortest paths from a source vertex in a weighted graph. It initializes distances, relaxes edges, checks for negative weight cycles, and prints the shortest distances. The program takes user input for the number of vertices, the adjacency matrix, and the source vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views2 pages

Java Implementation of Bellman-Ford Algorithm

The document contains a Java implementation of the Bellman-Ford algorithm for finding the shortest paths from a source vertex in a weighted graph. It initializes distances, relaxes edges, checks for negative weight cycles, and prints the shortest distances. The program takes user input for the number of vertices, the adjacency matrix, and the source vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

Scanner;

public class BellmanFord {


private int D[];
private int NoV;
public static final int MAX_VALUE = 999;

public BellmanFord(int NoV) {


[Link] = NoV;
D = new int[NoV + 1];
}

public void BellmanFordEvaluation(int source, int A[][]) {


for (int node = 1; node <= NoV; node++) {
D[node] = MAX_VALUE;
}
D[source] = 0;

// Relax edges (NoV - 1) times


for (int node = 1; node <= NoV - 1; node++) {
for (int i = 1; i <= NoV; i++) {
for (int j = 1; j <= NoV; j++) {
if (A[i][j] != MAX_VALUE) {
if (D[j] > D[i] + A[i][j]) {
D[j] = D[i] + A[i][j];
}
}
}
}
}

// Check for negative weight cycles


for (int i = 1; i <= NoV; i++) {
for (int j = 1; j <= NoV; j++) {
if (A[i][j] != MAX_VALUE) {
if (D[j] > D[i] + A[i][j]) {
[Link]("The Graph contains negative edge cycle");
return;
}
}
}
}

// Print shortest distances


for (int vertex = 1; vertex <= NoV; vertex++) {
[Link]("Distance of source " + source + " to " + vertex + " is " +
D[vertex]);
}
}

public static void main(String... arg) {


int NoV = 0;
int source;
Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of vertices");


NoV = [Link]();

int A[][] = new int[NoV + 1][NoV + 1];


[Link]("Enter the adjacency matrix");
for (int i = 1; i <= NoV; i++) {
for (int j = 1; j <= NoV; j++) {
A[i][j] = [Link]();
}
}

[Link]("Enter the source vertex");


source = [Link]();

BellmanFord bellmanford = new BellmanFord(NoV);


[Link](source, A);

[Link]();
}
}

You might also like