Bellman Ford Java - rFronteddu/general_wiki GitHub Wiki

import java.util.Arrays;
import lombock.AllArgsConstructor 

public class BellmanFord 
{
    @AllArgsConstructor
    static class Edge {
        int source;
        int destination;
        int weight;
    }

    static boolean bellmanFord(Edge[] edges, int source, int vertices) {
        // init
        int[] distance = new int[vertices];
        Arrays.fill (distance, Integer.MAX_VALUE);
        distance[source] = 0;

        // relax edges |V|-1 times
        for (int i = 1; i < vertices; i++) {  
            for (var e: edges) {
                int u = e.source;
                int v = e.destination;
                int w = e.weight;

                if (distance[u] != Integer.MAX_VALUE && distance[u] + w < distance[v]) {
                    distance[v] = distance[u] + w;
                }
            }
        }

        // check for negative-weight cycles
        for (var e : edges) {
            int u = e.source;
            int v = e.destination;
            int w = e.weight;
            if (distance[u] != Integer.MAX_VALUE && distance[u] + w < distance[v]) {
                // graph contains negative weight cycle
                return false;
            }
        }
        printSolution(distance, vertices);
        return true;
    }

    static void printSolution(int[] distance, int vertices) {
        System.out.println ("Vertex Distance From Source")
        for (int i = 0; i < vertices; i++) {
            System.out.println (i + "\t\t" + distance[i]);
        }
    }
}