Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Last active July 29, 2019 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/bf5e1c21d107ccebb2bd3ec2e7ec1180 to your computer and use it in GitHub Desktop.
Save RitamChakraborty/bf5e1c21d107ccebb2bd3ec2e7ec1180 to your computer and use it in GitHub Desktop.
Bellman-Ford Algorithm in Java
import java.util.Arrays;
public class BellmanFordAlgorithm {
public static void main(String[] args) {
int inf = Short.MAX_VALUE;
int[][] weights = new int[][] {
{0, 6, 5, 5, inf, inf, inf},
{inf, 0, inf, inf, -1, inf, inf},
{inf, -2, 0, inf, 1, inf, inf},
{inf, inf, -2, 0, inf, -1, inf},
{inf, inf, inf, inf, 0, inf, 3},
{inf, inf, inf, inf, inf, 0, 3},
{inf, inf, inf, inf, inf, inf, 0}
};
int[] costs = new int[] {0, inf, inf, inf, inf, inf, inf};
for (int k = 0; k < costs.length; k++) {
for (int i = 0; i < weights.length; i++) {
for (int j = 0; j < weights[0].length; j++) {
if (i != j) {
int newCost = costs[i] + weights[i][j];
if (costs[j] > newCost) {
costs[j] = newCost;
}
}
}
}
}
System.out.println("Costs: " + Arrays.toString(costs));
}
private static void graphPrinter(int[][] graphs) {
for (int[] graph: graphs) {
System.out.println(Arrays.toString(graph));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment