|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class BellmanFord { |
| 4 | + // Function implementing the Bellman-Ford algorithm |
| 5 | + public static void bellmanFord(int vertices, int edges[][], int source) { |
| 6 | + // Array to hold the shortest distances |
| 7 | + int dist[] = new int[vertices]; |
| 8 | + |
| 9 | + // Initialize all distances to infinity, except for the source vertex |
| 10 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 11 | + dist[source] = 0; |
| 12 | + |
| 13 | + // Step 1: The initial run over all edges in the graph |
| 14 | + for (int i = 1; i < vertices - 1; i++) { |
| 15 | + for (int[] edge : edges) { |
| 16 | + int u = edge[0]; // Starting vertex |
| 17 | + int v = edge[1]; // Ending vertex |
| 18 | + int weight = edge[2]; // Edge weight |
| 19 | + |
| 20 | + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { |
| 21 | + dist[v] = dist[u] + weight; |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // Step 2: Check for negative-weight cycles |
| 27 | + for (int[] edge : edges) { |
| 28 | + int u = edge[0]; |
| 29 | + int v = edge[1]; |
| 30 | + int weight = edge[2]; |
| 31 | + |
| 32 | + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { |
| 33 | + System.out.println("Graph contains negative weight cycle"); |
| 34 | + return; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Print the shortest distances for all vertices |
| 39 | + System.out.println("Vertex Distance from Source"); |
| 40 | + for (int i = 0; i < vertices; i++) { |
| 41 | + System.out.println(i + "\t\t" + dist[i]); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public static void main(String[] args) { |
| 46 | + // Number of vertices in the graph |
| 47 | + int vertices = 5; |
| 48 | + int edges[][] = { |
| 49 | + {0, 1, -1}, // Edge from vertex 0 to vertex 1 with weight -1 |
| 50 | + {0, 2, 4}, // Edge from vertex 0 to vertex 2 with weight 4 |
| 51 | + {1, 2, 3}, // Edge from vertex 1 to vertex 2 with weight 3 |
| 52 | + {1, 3, 2}, // Edge from vertex 1 to vertex 3 with weight 2 |
| 53 | + {1, 4, 2}, // Edge from vertex 1 to vertex 4 with weight 2 |
| 54 | + {3, 2, 5}, // Edge from vertex 3 to vertex 2 with weight 5 |
| 55 | + {3, 1, 1}, // Edge from vertex 3 to vertex 1 with weight 1 |
| 56 | + {4, 3, -3} // Edge from vertex 4 to vertex 3 with weight -3 |
| 57 | + }; |
| 58 | + |
| 59 | + // The source vertex |
| 60 | + int source = 0; |
| 61 | + |
| 62 | + // Call the Bellman-Ford algorithm |
| 63 | + bellmanFord(vertices, edges, source); |
| 64 | + } |
| 65 | +} |
0 commit comments