Last active
July 29, 2019 19:43
-
-
Save RitamChakraborty/bf5e1c21d107ccebb2bd3ec2e7ec1180 to your computer and use it in GitHub Desktop.
Bellman-Ford Algorithm in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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