|
| 1 | +package ShortestPath; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +class Edge { |
| 6 | + int source; |
| 7 | + int dest; |
| 8 | + int weight; |
| 9 | + |
| 10 | + public Edge(int source, int dest, int weight) { |
| 11 | + this.source = source; |
| 12 | + this.dest = dest; |
| 13 | + this.weight = weight; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +public class BellmanFords { |
| 18 | + |
| 19 | + public static void printPath(int parent[], int v) { |
| 20 | + if (v < 0) return; |
| 21 | + |
| 22 | + printPath(parent, parent[v]); |
| 23 | + System.out.print(v + " "); |
| 24 | + } |
| 25 | + |
| 26 | + public static void BellmanFord(List<Edge> edges, int source, int N) { |
| 27 | + int E = edges.size(); |
| 28 | + |
| 29 | + int distance[] = new int[N]; |
| 30 | + int parent[] = new int[N]; |
| 31 | + |
| 32 | + Arrays.fill(distance, Integer.MAX_VALUE); |
| 33 | + distance[source] = 0; |
| 34 | + |
| 35 | + Arrays.fill(parent, -1); |
| 36 | + int K = N; |
| 37 | + while (--K > 0) { |
| 38 | + for(int j=0; j<E; j++) { |
| 39 | + int u = edges.get(j).source; |
| 40 | + int v = edges.get(j).dest; |
| 41 | + int w = edges.get(j).weight; |
| 42 | + |
| 43 | + if (distance[u] != Integer.MAX_VALUE && (distance[u]+w) < distance[v]) { |
| 44 | + distance[v] = distance[u] + w; |
| 45 | + parent[v] = u; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /// Check for negative weight cycles |
| 51 | + for(int i=0; i<E; i++) { |
| 52 | + int u = edges.get(i).source; |
| 53 | + int v = edges.get(i).dest; |
| 54 | + int w = edges.get(i).weight; |
| 55 | + |
| 56 | + if (distance[u] != Integer.MAX_VALUE && (distance[u]+w) < distance[v]) { |
| 57 | + System.out.println("Negative weight cycle Found!!"); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + for (int i=0; i<N; i++) { |
| 62 | + System.out.print("Distance of vertex " + i + " from the source is " + distance[i] + ". It's path is [ "); |
| 63 | + printPath(parent, i); |
| 64 | + System.out.println("]"); |
| 65 | + } |
| 66 | + |
| 67 | + } |
| 68 | + |
| 69 | + public static void main(String[] args) { |
| 70 | + List<Edge> edges = Arrays.asList( |
| 71 | + new Edge(0, 1,-1), new Edge(0, 2, 4), |
| 72 | + new Edge(1, 2, 3), new Edge(1, 3, 2), |
| 73 | + new Edge(1, 4, 2), new Edge(3, 2, 5), |
| 74 | + new Edge(3, 1, 1), new Edge(4, 3,-3) |
| 75 | + ); |
| 76 | + int source = 0; |
| 77 | + int N = 5; |
| 78 | + |
| 79 | + BellmanFord(edges, source, N); |
| 80 | + } |
| 81 | +} |
0 commit comments